Open file in rich text box with C#

2019-01-26 15:04发布

问题:

This question have been answered. I recommend sumit_programmers solution below. 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#. 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. If the encoding is UTF-8 without byte order mark (BOM), it seems "Encoding.Default" doesn't work, though. For more information, go to 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);
    }
  }
}

回答1:

Yes, you are getting that error as you are trying to access file that can't be loaded in Rich Text Box. If you want to load a .rtf file you need to add this line

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

and if you want to load .txt file, you need to add this

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


回答2:

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:

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

See the doc for ReadAllText for more info.

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). 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:

You could just change the MessageBox.Show to the line:

rtfMain.LoadFile(dlg.FileName);

Probably adding in suitable try/catch to handle any errors in reading the file.

See the documentation for RichTextBox.LoadFile for a complete sample.



回答3:

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