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

MCS*_*arp 3 c# wpf openfiledialog richtextbox

我试图打开一个文件来查看内容里面一个纯文本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);
    }
}
Run Code Online (Sandbox Code Playgroud)

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

我喜欢的行为类似于打开.rtf,选择所有文本,并将结果粘贴到RichTextbox.如何点击按钮才能做到这一点?

Abd*_*Haj 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();
  }
}
Run Code Online (Sandbox Code Playgroud)