read a file in csharp

To read a file in C#, you can use the StreamReader class from the System.IO namespace. Here's an example code that reads a text file line by line:

main.cs
using System.IO;

// path to the file to read
string filePath = "path/to/file.txt";

// create a StreamReader object to read the file
using (StreamReader reader = new StreamReader(filePath))
{
    // read the file line by line
    string line;
    while ((line = reader.ReadLine()) != null)
    {
        // do something with each line, e.g. print it to the console
        Console.WriteLine(line);
    }
}
407 chars
17 lines

In the above code, we first specify the file path to the text file that we want to read. Then we create a StreamReader object and pass the file path to its constructor. We use a using block to ensure that the StreamReader object is properly disposed of after use.

Inside the using block, we use a while loop to read the file line by line. On each iteration of the loop, we read the next line using the ReadLine method of the StreamReader object. If the line is not null (i.e. if we haven't reached the end of the file yet), we can do something with the line, such as print it to the console.

Note that the StreamReader class also provides other methods for reading files, such as Read, which reads a specified number of characters from the file instead of an entire line.

gistlibby LogSnag