我正在尝试打开一个文件以在 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
中。我如何通过单击按钮来做到这一点?
最佳答案
使用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();
}
}
关于c# - WPF Richtextbox 以纯文本格式打开 RTF 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14443295/