docxx
docxx

Reputation: 93

Opening text file in c#

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

Upvotes: 3

Views: 20681

Answers (4)

BlazE
BlazE

Reputation: 91

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!

Upvotes: 2

sshow
sshow

Reputation: 9084

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

Upvotes: 2

kelloti
kelloti

Reputation: 8941

Use File.ReadAllText

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

Upvotes: 2

kevingessner
kevingessner

Reputation: 18985

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

Upvotes: 4

Related Questions