C# WPF Richtextbox以纯文本形式打开RTF文件
我试图打开一个文件,在C# WPF Richtextbox以纯文本形式打开RTF文件,c#,wpf,richtextbox,openfiledialog,C#,Wpf,Richtextbox,Openfiledialog,我试图打开一个文件,在按钮上单击以查看RichTextbox中的纯文本内容。似乎没有什么能正常工作 private void loadFile_Click(object sender, RoutedEventArgs e) { OpenFileDialog openFile1 = new OpenFileDialog(); openFile1.FileName = "Document"; openFile1.DefaultExt = "*.*"; openFil
按钮上单击以查看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
。如何通过单击按钮来实现这一点?您是否尝试过使用richTextbox1.AppendText(File.ReadAllText(openFile1.FileName))
?使用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();
}
}
与@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();
}
}
我认为您需要在Word中打开文件,选择所有文本并将RTB文本设置为内容。比如说,如果你在记事本中打开一个.doc或.rtf文件,你会看到所有你不想要的头字符(“没有看到文件格式中添加的代码”)有没有办法在不打开文件的情况下执行此操作?请注意,您不能简单地将.doc
或.docx
文件加载到RichTextBox
中。这些类型不包含RTF格式的文本,因此必须先将它们保存为RTF文件…尝试将System.Windows.DataFormats.text
更改为System.Windows.DataFormats.Rtf
这将打开文件并读取为Rtf。但是,它不会粘贴纯文本,也不会与其他格式(如.doc和.docxI)一起使用。docx文件无法在richtextbox中打开,因此已编辑标题以将Rtf文件作为纯文本打开。这是最好的答案。此答案应转换为纯文本。请使用range.ClearAllProperties()
这样做。将RTF文件转换为纯文本的伟大WPF解决方案。使用range.text作为纯文本输出。Google花了大约10次尝试找到它。这对RTF文档和条带格式非常有用。如何将其应用于Word文档格式?简短的回答是,您必须先将.Doc或.docx转换为RTF。请参阅.ARichTextbox
支持RTF,Word.doc和.docx的功能比RTFit慢,但您可以尝试以下功能:RichTextbox.Selection.Load(stream,DataFormats.RTF);