简体   繁体   中英

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

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

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

使用File.ReadAllText

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

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM