WPF Richtextbox以纯文本格式打开RTF文件

时间:2013-01-21 16:44:15

标签: c# wpf richtextbox openfiledialog

我正在尝试打开一个文件,在RichTextbox点击的Button内以纯文本形式查看内容。似乎没有什么工作正常。

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,选择所有文本,并将结果粘贴到RichTextbox。如何通过点击按钮来实现这一目标?

3 个答案:

答案 0 :(得分:6)

使用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();
  }
}

答案 1 :(得分:0)

您是否尝试过使用richTextbox1.AppendText(File.ReadAllText(openFile1.FileName))

答案 2 :(得分: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();
        }
    }