This example shows you How to Read Text File in C# using File and StreamReader class.

How to Read Text File in C#

To read a text file in c # language you can use a variety of ways.

The simple way is to use the File class of the System.IO namespace.

string fileName = @"d:\file.txt";
string text = File.ReadAllText(fileName, Encoding.UTF8);

and don't forget to include the System.IO namespace.

How to Read Text File into String using StreamReader in C#

You can also use StreamReader for reading lines of information from a standard text file. StreamReader is designed for character input in a particular encoding, whereas the Stream class is designed for byte input and output.

public void OpenTextFile(string fileName)
{
    string text;
    using (FileStream fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read))
    {
        using (var streamReader = new StreamReader(fileStream, Encoding.UTF8))
        {
            text = streamReader.ReadToEnd();
        }
    }
}

How to Read Text File into String Array in C#

If you can to read text files into string array you can use the File class of System.IO namespace.

string fileName = @"c:\file.txt";
string[] lines = File.ReadAllLines(fileName, Encoding.UTF8);

You can also read text file line by line in c# by using foreach loop to get the line value.

foreach (string line in lines)
{
    //Process your data here
}

How to Read Text File into String Array using StreamReader in C#

If you want to use the StreamReader class to read text files into string array you can easily write your c# code as the following.

public string[] ReadTextFileToArrays(string fileName)
{
    string[] lines;
    var list = new List<string>();
    using (FileStream fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read))
    {
        using (StreamReader streamReader = new StreamReader(fileStream, Encoding.UTF8))
        {
            string line;
            while ((line = streamReader.ReadLine()) != null)
            {
                list.Add(line);
            }
        }
    }
    lines = list.ToArray();
    return lines;
}

You should check the line is not null, then you will add to the line array.