简体   繁体   English

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

[英]Open file in rich text box with C#

This question have been answered. 这个问题已得到解答。 I recommend sumit_programmers solution below. 我推荐下面的sumit_programmers解决方案。 For now, I've removed my code, thinking it's more confusing than helpful. 现在,我已经删除了我的代码,认为它更令人困惑而不是有用。 When I've developed it a bit further, perhaps I'll post my code here, with some comments. 当我进一步开发它时,也许我会在这里发布我的代码,并附上一些评论。

You may also be interested in the answer to the question Save text from rich text box with C# . 您可能还对使用C#从富文本框中保存文本的问题的答案感兴趣。 There is an answer that reminds of the accepted answer to this question. 有一个答案让人想起这个问题的答案。 The code should work, but it's written by me, so there may be some errors or missing information. 代码应该可以工作,但它是由我编写的,因此可能存在一些错误或缺少信息。


Update: I have improved the code a bit (at least I think so). 更新:我对代码进行了一些改进(至少我认为是这样)。 "Encoding.Default" seems to work with most common encodings, like ANSI. “Encoding.Default”似乎适用于最常见的编码,如ANSI。 If the encoding is UTF-8 without byte order mark (BOM), it seems "Encoding.Default" doesn't work, though. 如果编码是UTF-8而没有字节顺序标记(BOM),那么似乎“Encoding.Default”不起作用。 For more information, go to informit.com/guides . 有关更多信息,请访问informit.com/guides Here's the code I'm using right now: 这是我现在正在使用的代码:

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);
    }
  }
}

Yes, you are getting that error as you are trying to access file that can't be loaded in Rich Text Box. 是的,当您尝试访问无法在Rich Text Box中加载的文件时,您收到该错误。 If you want to load a .rtf file you need to add this line 如果要加载.rtf文件,则需要添加此行

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

and if you want to load .txt file, you need to add this 如果要加载.txt文件,则需要添加此文件

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

Sample Code: 示例代码:

 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)
            {
            }
        }

Edit: Ok, if you want to open a plain text file, go back to my original solution. 编辑:好的,如果要打开纯文本文件,请返回原始解决方案。

You could just change the MessageBox.Show to the line: 您可以将MessageBox.Show更改为该行:

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

See the doc for ReadAllText for more info. 有关详细信息,请参阅ReadAllText的文档。

The try/catch bit is to avoid having your app crash due to unhandled errors (sometimes it might be the best thing to do to just let it crash, but even then you usually want to close it down in a somewhat controlled manner). try / catch位是为了避免因未处理的错误导致应用程序崩溃(有时候让它崩溃可能是最好的办法,但即便如此,你通常也想以一种有点控制的方式关闭它)。 Especially when working with files, there's a high risk that they'll fail to load for some reason so it might be useful to surround the code with some error handling, for example something like this: 特别是在处理文件时,由于某些原因,它们很有可能无法加载,因此通过一些错误处理来包围代码可能很有用,例如:

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);
}

Old answer below 下面的老答案

Edit: I forgot that it's a RichTextBox, so my first answer wasn't as suitable, so it's probably better to do this instead: 编辑:我忘了它是一个RichTextBox,所以我的第一个答案不合适,所以最好这样做:

You could just change the MessageBox.Show to the line: 您可以将MessageBox.Show更改为该行:

rtfMain.LoadFile(dlg.FileName);

Probably adding in suitable try / catch to handle any errors in reading the file. 可能添加适当的try / catch来处理读取文件时的任何错误。

See the documentation for RichTextBox.LoadFile for a complete sample. 有关完整示例,请参阅RichTextBox.LoadFile的文档。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM