How to read a file in C# .NET

In VB6 and C++, you had to open a file and read line by line, .NET (Both C# and VB) have a number of functions that allow you to read the contents of a file. The traditional way to read a file would be to open the file and read a line by line and that will be our first example. First though, we need to include the reference commands but there's only one needed.

using System.IO;

As mentioned above, the first example of how to read a file is to read line by line.

using(StreamReader iFS = new StreamReader("C:\\temp\\demo.txt"))
{
    while(iFS.EndOfStream== false)
    {
        sLine = iFS.ReadLine();
        Console.WriteLine(sLine);
    }
}

When the code gets to the closing bracket, the file will be closed so you don't have to do :-

iFS.Close();

If you plan to do some other processing rather than just printing it and need to store the lines in memory, you can use :-

string[] sLines;
sLines = File.ReadAllLines("C:\\temp\\demo.txt");

The result of the above command will be an array containing a line in each element. To get the count of line, just do a GetUpperBound on the array such as :-

int iLines = sLines.GetUpperBound(0);

The last solution is to load the whole contents of the file into one variable and then you do the splitting or what ever you want.

string sText = File.ReadAllText("C:\\temp\\demo.txt");

Tags - .NET   File

Last Modified : June 2023


About... / Contact.. / Cookie...