繁体   English   中英

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

[英]WPF Richtextbox open RTF file as plain text

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

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

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

与@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();
        }
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM