-2

i write the following code to open txt file

private void button1_Click(object sender, EventArgs e)
{
    try
    {
        OpenFileDialog reader = new OpenFileDialog();

        reader.Filter = "txt files (*.txt)|*.txt";
        // reader.Title = "";
        reader.ShowDialog();
        rtb1.LoadFile(reader.FileName);
    }
    catch(Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
}      

but this code is give the following error:
Error:
File format is not valid

Agustin Meriles
  • 4,866
  • 3
  • 29
  • 44
  • 1
    @Igor Probably `RichTextBox`. It's possible the error is thrown, because you're loading a `.txt` instead of a `.rtf`, referr to this site for more info: http://msdn.microsoft.com/en-us/library/3f99sst7.aspx – Nolonar Apr 04 '13 at 13:29
  • @lgor: This is rich text box – Zia Rehman Apr 04 '13 at 13:29
  • @ZiaRehman - what is the content of selected txt file? – Igor Apr 04 '13 at 13:31
  • If you work with a dialog, you probably want to check the `DialogResult` like this: `if (reader.ShowDialog() == DialogResult.OK) { \\work with reader.FileName }`. To read the whole file into a `string` use: `System.IO.File.ReadAllText(reader.FileName)`. – Corak Apr 04 '13 at 13:34
  • @nolonar can't a rich text box accept plain text? Or does it have to be wrapped in `\rtf{...}`? – Cole Tobin Apr 04 '13 at 14:19
  • @ColeJohnson It can, but apparently, the `RichTextBox.LoadFile()` method only accepts `.rtf` files. I think Luke Marlin's answer pretty much explains how to pass on `.txt` files without the method throwing an exception. – Nolonar Apr 04 '13 at 14:22

1 Answers1

5

As suggested in some useful comments, the error comes from:

rtb1.LoadFile(reader.FileName);

RichTextBox.LoadFile takes an RTF file, not a .txt, and you get an ArgumentException which is explained by MSDN :

"The file being loaded is not an RTF document."

If you want to load a txt file, use this :

rtb1.LoadFile(reader.FileName, RichTextBoxStreamType.PlainText)

and it should work.

Luke Marlin
  • 1,398
  • 9
  • 26