Reading From a Text File in C#

To read a text file one line at a time you can do like this:

using System.IO;

using (var reader = new StreamReader(fileName))
{
    string line;
    while ((line = reader.ReadLine()) != null)
    {
        // Do stuff with your line here, it will be called for each 
        // line of text in your file.
    }
}

There are other ways as well. For example, if the file isn’t too big and you just want everything read to a single string, you can use File.ReadAllText()

myTextBox.Text = File.ReadAllText(fileName);

Leave a Comment