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

mat*_*lof 7 c# file-io richtextbox winforms

这个问题已得到解答.我推荐下面的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);
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

sum*_*mer 17

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

richTextBox1.LoadFile(dlg.FileName, RichTextBoxStreamType.RichText);
Run Code Online (Sandbox Code Playgroud)

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

richTextBox1.LoadFile(dlg.FileName, RichTextBoxStreamType.PlainText);
Run Code Online (Sandbox Code Playgroud)

示例代码:

 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)
            {
            }
        }
Run Code Online (Sandbox Code Playgroud)