使用C#在富文本框中打开文件

这个问题已得到解答。 我推荐下面的sumit_programmers解决方案。 现在,我已经删除了我的代码,认为它比有用的更令人困惑。 当我进一步开发它时,也许我会在这里发布我的代码,并附上一些评论。

您可能还对使用C#从富文本框中保存文本的问题的答案感兴趣。 有一个答案让人想起这个问题的答案。 代码应该可以工作,但它是由我编写的,因此可能存在一些错误或缺少信息。


更新:我对代码进行了一些改进(至少我认为是这样)。 “Encoding.Default”似乎适用于最常见的编码,如ANSI。 如果编码是UTF-8而没有字节顺序标记(BOM),那么似乎“Encoding.Default”不起作用。 有关更多信息,请访问informit.com/guides 。 这是我现在正在使用的代码:

private void fileOpen_Click(object sender, EventArgs e) { using (OpenFileDialog dlgOpen = new OpenFileDialog()) { try { // Available file extensions dlgOpen.Filter = "All files(*.*)|*.*"; // Initial directory dlgOpen.InitialDirectory = "D:"; // OpenFileDialog title dlgOpen.Title = "Open"; // Show OpenFileDialog box if (dlgOpen.ShowDialog() == DialogResult.OK) { // Create new StreamReader StreamReader sr = new StreamReader(dlgOpen.FileName, Encoding.Default); // Get all text from the file string str = sr.ReadToEnd(); // Close the StreamReader sr.Close(); // Show the text in the rich textbox rtbMain rtbMain.Text = str; } } catch (Exception errorMsg) { MessageBox.Show(errorMsg.Message); } } } 

是的,当您尝试访问无法在RTF文本框中加载的文件时,您收到该错误。 如果要加载.rtf文件,则需要添加此行

 richTextBox1.LoadFile(dlg.FileName, RichTextBoxStreamType.RichText); 

如果要加载.txt文件,则需要添加此文件

 richTextBox1.LoadFile(dlg.FileName, RichTextBoxStreamType.PlainText); 

示例代码:

  using (OpenFileDialog ofd = new OpenFileDialog()) { try { ofd.Filter = "Text files (*.txt)|*.txt|RTF files (*.rtf)|*.rtf"; if (ofd.ShowDialog() == DialogResult.OK) { if (Path.GetExtension(ofd.FileName) == ".rtf") { richTextBox1.LoadFile(ofd.FileName, RichTextBoxStreamType.RichText); } if (Path.GetExtension(ofd.FileName) == ".txt") { richTextBox1.LoadFile(ofd.FileName, RichTextBoxStreamType.PlainText); } } } catch (Exception ex) { } } 

编辑:好的,如果要打开纯文本文件,请返回原始解决方案。

您可以将MessageBox.Show更改为该行:

 rtfMain.Text = File.ReadAllText(dlg.FileName); 

有关详细信息,请参阅ReadAllText的文档。

try / catch位是为了避免因未处理的错误导致应用程序崩溃(有时候让它崩溃可能是最好的办法,但即便如此,你通常也希望以一种有些受控的方式关闭它)。 特别是在处理文件时,由于某种原因它们很难加载,所以用一些error handling来包围代码可能是有用的,例如:

 try { rtfMain.Text = File.ReadAllText(dlg.FileName); } catch(Exception ex) // should try to avoid catching generic Exception here and use a more specialized one { MessageBox.Show("Failed to open file. Error: " + ex.Message); } 

下面的老答案

编辑:我忘了它是一个RichTextBox,所以我的第一个答案不合适,所以最好这样做:

您可以将MessageBox.Show更改为该行:

 rtfMain.LoadFile(dlg.FileName); 

可能添加适当的try / catch来处理读取文件时的任何错误。

有关完整示例,请参阅RichTextBox.LoadFile的文档。

 try { openFileDialog fd=new openFileDialog(); fd.showDialog(); richTextbox1.LoadFile(fd.FileName); } catch(Exception exc) { MessageBox.Show(exc.Message); }