这个问题已经回答了。我在下面推荐 sumit_programmers 解决方案。现在,我删除了我的代码,认为它更令人困惑而不是有用。当我进一步开发它时,也许我会在这里发布我的代码,并附上一些评论。
您可能也对 Save text from rich text box with C# 问题的答案感兴趣.有一个答案让人想起这个问题的公认答案。代码应该可以运行,但它是我编写的,因此可能存在一些错误或缺少信息。
更新:我对代码做了一些改进(至少我是这么认为的)。 “Encoding.Default”似乎适用于最常见的编码,如 ANSI。如果编码是没有字节顺序标记 (BOM) 的 UTF-8,那么“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 文件,你需要添加这一行
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)
{
}
}
关于c# - 使用 C# 在富文本框中打开文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3743438/