read in a file in csharp

To read a file in C#, you can use the StreamReader class.

Here's an example code snippet that demonstrates how to read in a file using StreamReader:

main.cs
string path = @"C:\path\to\file.txt";

// Open the file using a stream reader.
using (StreamReader reader = new StreamReader(path))
{
    // Read the entire file into a string.
    string fileContents = reader.ReadToEnd();
    
    // Do something with the file contents.
    Console.WriteLine(fileContents);
}
311 chars
12 lines

In this example, we first specify the path to the file that we'd like to read using a string variable called path. We then create a new instance of the StreamReader class and pass the file path to its constructor. We use a using statement to ensure that the StreamReader object is properly disposed of when we're done reading the file.

Within the using block, we call the ReadToEnd method of the StreamReader object to read the entire file into a string variable called fileContents. Finally, we can do whatever we want with the file contents - in this case, we simply print them to the console.

related categories

gistlibby LogSnag