3

When I try to open a .txt file it only shows its location in my textbox. I am out of ideas:( hope you can help me...

code:

private void OpenItem_Click(object sender, EventArgs e)
{
    openFileDialog1.ShowDialog();
    System.IO.StringReader OpenFile = new System.IO.StringReader(openFileDialog1.FileName);
    richTextBox1.Text = OpenFile.ReadToEnd();
    OpenFile.Close();
}

4 Answers 4

4

A StringReader reads the characters from the string you pass to it -- in this case, the file's name. If you want to read the contents of the file, use a StreamReader:

var OpenFile = new System.IO.StreamReader(openFileDialog1.FileName);
richTextBox1.Text = OpenFile.ReadToEnd();
2

Use File.ReadAllText

richTextBox1.Text = File.ReadAllText(openFileDialog1.FileName);
2

I'd use the File.OpenText() method for reading text-files. You should also use using statements to properly dispose the object.

if(openFileDialog1.ShowDialog() == DialogResult.OK)
{
    try
    {
        // Make sure a file was selected
        if ((myStream = openFileDialog1.OpenFile()) != null) {
            // Open stream
            using (StreamReader sr = File.OpenText(openFileDialog1.FileName)) 
            {
                // Read the text
                richTextBox1.Text = sr.ReadToEnd();
            }
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show("An error occured: " + ex.Message);
    }
}
2

That's easy. This is what you need to do:

1) Put using System.IO; above namespace.

2) Create a new method:

    public static void read()
    {
         StreamReader readme = null;

         try
         {
              readme = File.OpenText(@"C:\path\to\your\.txt\file.txt");
              Console.WriteLine(readme.ReadToEnd());
         }
         // will return an invalid file name error
         catch (FileNotFoundException errorMsg)
         {
              Console.WriteLine("Error, " + errorMsg.Message);
         }
         // will return an invalid path error
         catch (Exception errorMsg)
         {
             Console.WriteLine("Error, " + errorMsg.Message);
         }
         finally
         {
              if (readme != null)
              {
                  readme.Close();
              }
         }
    }

3) Call it in your main method: read();

4) You're done!

1
  • 1
    You do realize that a 'using' statement would make your entire finally block obsolete, right? After all, that was what they were made to do. Plus, you are quite late to the party here. Was there really any need to resurrect this question from the grave? Dec 2, 2013 at 17:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.