[英]WPF Richtextbox open RTF file as plain text
I am trying to open a file to view the contents as plain text inside a RichTextbox
on a Button
click. 我正在尝试打开一个文件,以便在Button
单击时以RichTextbox
内的纯文本形式查看内容。 Nothing seems to work properly. 似乎没有什么工作正常。
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);
}
}
I am using WPF and the LoadFile method doesn't work. 我使用WPF并且LoadFile方法不起作用。 I'd like to be able to select a file from the OpenFileDialog
and have it be loaded as plain text inside the RichTextbox
. 我希望能够从OpenFileDialog
选择一个文件,并将其作为纯文本加载到RichTextbox
。 Without seeing added code from file formats. 没有看到来自文件格式的添加代码。
The behavior I'd like is similar to opening an .rtf, selecting all text, and pasting that result into the RichTextbox
. 我喜欢的行为类似于打开.rtf,选择所有文本,并将结果粘贴到RichTextbox
。 How can I do that with a button click? 如何点击按钮才能做到这一点?
Use TextRange
and FileStream
使用TextRange
和FileStream
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))
?
Similar to @AbZy, you need to clear the formatting first: 与@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.