To read a text file in C#, you can use the StreamReader class from the System.IO namespace. Here is an example code snippet that demonstrates this:
main.cs544 chars24 lines
In this code, we first import the System.IO namespace, which provides file input and output functionality. Then, we use a try-catch block to handle any exceptions that might occur during the file reading process.
Inside the try block, we create an instance of the StreamReader class and pass the name of the file we want to read as a string parameter to its constructor. Then, we call the ReadToEnd method of the StreamReader instance to read the entire contents of the file as a string, which we then print to the console.
Finally, we close the StreamReader instance using a using statement, which automatically disposes of the object once we're done using it. If an exception occurs during the file reading process, we catch it in the catch block and print a message to the console.
gistlibby LogSnag