3

我正在尝试打开一个文件以RichTextboxButton单击时将内容作为纯文本查看。似乎没有什么工作正常。

private void loadFile_Click(object sender, RoutedEventArgs e)
{
    OpenFileDialog openFile1 = new OpenFileDialog();
    openFile1.FileName = "Document"; 
    openFile1.DefaultExt = "*.*";
    openFile1.Filter = "All Files|*.*|Rich Text Format|*.rtf|Word Document|*.docx|Word 97-2003 Document|*.doc";

    if (openFile1.ShowDialog() == System.Windows.Forms.DialogResult.OK && openFile1.FileName.Length > 0)
    {
        //richTextbox1.Document.ContentStart = File.ReadAllText(openFile1.FileName);
    }
}

我正在使用 WPF,并且 LoadFile 方法不起作用。我希望能够从中选择一个文件OpenFileDialog并将其作为纯文本加载到RichTextbox. 没有从文件格式中看到添加的代码。

我想要的行为类似于打开 .rtf、选择所有文本并将结果粘贴到 .rtf 文件中RichTextbox。如何通过单击按钮来做到这一点?

4

3 回答 3

7

使用TextRangeFileStream

if (openFile1.ShowDialog() == System.Windows.Forms.DialogResult.OK )
{             
  TextRange range;
  System.IO.FileStream fStream;

  if (System.IO.File.Exists(openFile1.FileName))
  {
      range = new TextRange(RichTextBox1.Document.ContentStart, RichTextBox1.Document.ContentEnd);
      fStream = new System.IO.FileStream(openFile1.FileName, System.IO.FileMode.OpenOrCreate);
      range.Load(fStream, System.Windows.DataFormats.Rtf );

      fStream.Close();
  }
}
于 2013-01-21T16:56:00.233 回答
0

你试过使用richTextbox1.AppendText(File.ReadAllText(openFile1.FileName))吗?

于 2013-01-21T16:52:37.043 回答
0

与@AbZy 类似,您需要先清除格式:

    private void loadFile_Click(object sender, RoutedEventArgs routedEventArgs)
    {
        OpenFileDialog openFile1 = new OpenFileDialog();
        openFile1.FileName = "Document";
        openFile1.DefaultExt = "*.*";
        openFile1.Filter = "All Files|*.*|Rich Text Format|*.rtf|Word Document|*.docx|Word 97-2003 Document|*.doc";

        if (openFile1.ShowDialog() == true)
        {
            var range = new TextRange(rtf.Document.ContentStart, rtf.Document.ContentEnd);

            using (var fStream = new FileStream(openFile1.FileName, FileMode.OpenOrCreate))
            {
                // load as RTF, text is formatted
                range.Load(fStream, DataFormats.Rtf);
                fStream.Close();
            }
            // clear the formatting, turning into plain text
            range.ClearAllProperties();
        }
    }
于 2013-01-21T17:01:50.350 回答