Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# - Read .txt file into TextBox

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);
            }
        }
    }
like image 727
Jeagr Avatar asked Dec 16 '12 10:12

Jeagr


1 Answers

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

like image 50
user287107 Avatar answered Sep 20 '22 20:09

user287107