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.cs407 chars17 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