.NET Framework System.IO Reading a text file using StreamReader

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!


string fullOrRelativePath = "testfile.txt";

string fileData;

using (var reader = new StreamReader(fullOrRelativePath))
    fileData = reader.ReadToEnd();

Note that this StreamReader constructor overload does some auto encoding detection, which may or may not conform to the actual encoding used in the file.

Please note that there are some convenience methods that read all text from file available on the System.IO.File class, namely File.ReadAllText(path) and File.ReadAllLines(path).

Got any .NET Framework Question?