C# read file content code example

Example 1: c sharp how to read a text file

// To save the text as one string use 'ReadAllText()'
string text = System.IO.File.ReadAllText(@"C:\filepath\file.txt");
// To save each line seperately in an array use 'ReadAllLines()'
string[] lines = System.IO.File.ReadAllLines(@"C:\filepath\file.txt");

Example 2: read file c#

string text = File.ReadAllText(@"c:\file.txt", Encoding.UTF8);

Example 3: how to call last string from text file C#

If the file is not too large, just read the lines and pick the last:

string lastLine = File.ReadLines("pathToFile").LastOrDefault();