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

标签 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 中。我如何通过单击按钮来做到这一点?

最佳答案

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

关于c# - WPF Richtextbox 以纯文本格式打开 RTF 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14443295/

相关文章:

c# - c Sharp mysql 下划线、空格表名错误

c# - 静默安装 .msu Windows 更新?

WPF 圆角文本框

c# - 如何让FolderBrowserDialog仅显示网络

vb.net - 如何为 vb.net 的 richtextbox 中的单词制作自定义智能感知

.net - WinForms RichTextBox : how to reformat asynchronously, 没有触发 TextChanged 事件

c# - 我如何覆盖基类的 == 运算符,以便调用覆盖

c# - 何时使用多个类库?

c++ - Windows 通用应用程序 (XAML) : textBlock->Text cannot be called with the given argument list

c# - 在 Richtextbox 上禁用平滑滚动