If you want to learn how you can read text from a text file using C#, you have come to the right blog post.

In this one, we will go step by step and see how easily we can read a text file using C#

 

Why Read A Text File Using C#?

There are many scenarios where we have to read a file while creating our application or website using C# and ASP.NET

The use cases could be, you want to read an email template that is stored as a text file.

This could be some data that is stored in a text file as JSON format.

Let's see how we can read a text file using C#

File.ReadAllText("FILE_PATH")

In C#, if we want to read a file, we make use of the static class File which provides us a method called ReadAllText and ReadAllTextAsync.

This method takes one and two parameters. The mandatory parameter to this method is the location or path of the file. This is a string path of the file.

When given a string path to the file that you want to read, this method returns a string of text i.e. the content of the text file.

The second parameter is the Encoding, e.g. System.Text.Encoding.UTF8. When provided, this method reads all the text of the file with the specified encoding.

Example:

var fileText = File.ReadAllText(@"C:\ReadAllTextExample.txt"); Console.WriteLine(fileText); // Result: This is text saved inside the ReadAllTextExample.txt file.