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.cs311 chars12 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.
gistlibby LogSnag