C# - Read .txt file into TextBox

63,273

if you just need the complete text, you should use the function File.ReadAllText - pass it the FileName/Path selected in the dialoge (openFileDialog1.FileName).

to load for example the content into a textbox, you can write:

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

opening and using streams is a little bit more complicated, for that you should look up the using - statement

Share:
63,273
Jeagr
Author by

Jeagr

Updated on July 21, 2022

Comments

  • Jeagr
    Jeagr almost 2 years

    I am trying to read a .txt file into a multi-line text box with the following code. I have gotten the file dialog button to work perfectly, but I am not sure how to get the actual text from the fiile into the textbox. Here is my code. Can you help?

    private void button_LoadSource_Click(object sender, EventArgs e)
        {
            Stream myStream = null;
            OpenFileDialog openFileDialog1 = new OpenFileDialog();
    
            openFileDialog1.InitialDirectory = "c:\\";
            openFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
            openFileDialog1.FilterIndex = 2;
            openFileDialog1.RestoreDirectory = true;
    
            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    if ((myStream = openFileDialog1.OpenFile()) != null)
                    {
                        using (myStream)
                        {
                            // Insert code to read the stream here.
                        }
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
                }
            }
        }