Open file in rich text box with C#

非 Y 不嫁゛ 提交于 2019-11-29 10:51:06

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

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.

Vinoth K
try
{
 openFileDialog fd=new openFileDialog();
 fd.showDialog();
 richTextbox1.LoadFile(fd.FileName);
}
catch(Exception exc)
{
 MessageBox.Show(exc.Message);
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!