Reading a Text File in C# through Stream Reader



This C# program shows you how you can load an external Text File from your Hard Disk into a Multi-Line TextBox. The procedure consists of creating the StreamWriter object to begin working which is the feature of this code.  Watch the image above.


The coding begins with the choose path button. We use it to open up a OpenFileDialogBox which is used to retrieve the file path of an existing file on a hard disk. Opening it consists of invoking the Show() method. When the user successfully selects a valid file, the FileName property of the OpenFileDialogBox is updated to carry the full length String value of the file location. Then we save the file location in the textbox named txtChoose Watch the code:

private void btnChoose_Click(object sender, EventArgs e)
        {
            openFileDialog1.ShowDialog();
            txtChoose.Text = openFileDialog1.FileName.ToString();
        }


Now that we have the file location of the text file, we can load the text file Line by Line into the Multi-Line extbox. Note that when we create a textbox by default it is a single lined textbox. To make it Multi-Line simply change the Multiline property of the textbox to true. Watch the code below to create a StreamReader Object and fill the Multi-Line textbox subsequently:


private void btnLoadFile_Click(object sender, EventArgs e)
        {
            int counter = 0;
            string CurrentLine;

            // Read the file and display it line by line.
            System.IO.StreamReader FileToRead =
               new System.IO.StreamReader(txtChoose.Text);

            while ((CurrentLine = FileToRead.ReadLine()) != null)
            {
                MainTextBox.AppendText(CurrentLine);
                MainTextBox.AppendText("\n");
                counter++;
            }

            FileToRead.Close();

            Console.ReadLine();
        }


In the above code, we have a while loop to keep reading lines until we have reached to the end of the file. We append lines using the AppendText() function inside the for loop. This function does not write lines by default. This is because the text is read as a sequence of characters only. Thus to create the line by line effect, we add the AppendText("\n")  method.  Without this the text loaded would look inconsistent.

Do not forget to close the open file through the FileToRead.Close()  method. In case a file is open this program or any other program, you would not be able to edit it externally.

Please Note :
** Do not Copy & Paste code written here ; instead type it in your Development Environment
** Testing done in .Net 4.5 but code should be very similar for previous versions of .Net

** Direct Download Source Code Here