read a text file in csharp

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.cs
using System;
using System.IO;

class Program
{
    static void Main(string[] args)
    {
        try
        {
            // Open the text file using a stream reader
            using (StreamReader sr = new StreamReader("example.txt"))
            {
                // Read the entire file contents
                string contents = sr.ReadToEnd();
                Console.WriteLine(contents);
            }
        }
        catch (Exception e)
        {
            Console.WriteLine("Failed to read file: " + e.Message);
        }
    }
}
544 chars
24 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