C# Examples

Menu:


Read Text File [C#]

These examples show how to read whole text file into string, how to read all lines into string array or how to read text file line by line to decrease memory usage.

The following examples require to add namespace using System.IO;

Read Text File into String

It's super easy to read whole text file into string using static class File and its method File.ReadAllText.

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

Read Text File into String (with StreamReader)

Let's look under the hood of the previous example. Method File.ReadAllText is implemented similarly to the following code. The using statement ensures that method StreamReader.Dis­pose is called. The StreamReader's Dis­pose also calls FileStream.Dis­pose method which closes the file.

[C#]
string text;
var fileStream = new FileStream(@"c:\file.txt", FileMode.Open, FileAccess.Read);
using (var streamReader = new StreamReader(fileStream, Encoding.UTF8))
{
    text = streamReader.ReadToEnd();
}

Read Text File into String Array

Again, the easy way is to use static class File and it's method File.ReadAllLi­nes.

[C#]
string[] lines = File.ReadAllLines(@"c:\file.txt", Encoding.UTF8);

Read Text File into String Array (with StreamReader)

If you look under the hood of the File.ReadAllLines method, you can find implementation similar to this. As it was previously written, the using statement disposes StreamReader and FileStream (which closes the file).

[C#]
string[] lines;
var list = new List<string>();
var fileStream = new FileStream(@"c:\file.txt", FileMode.Open, FileAccess.Read);
using (var streamReader = new StreamReader(fileStream, Encoding.UTF8))
{
    string line;
    while ((line = streamReader.ReadLine()) != null)
    {
        list.Add(line);
    }
}
lines = list.ToArray();

Read Text File Line by Line

To reduce memory usage for large text files, you can process lines immediately instead of adding it to the list as in the previous example. To do that use File.ReadLines. This method internally creates Enumerator. Every time foreach asks for a next value, it calls StreamReader.Re­adLine under the hood.

[C#]
foreach (string line in File.ReadLines(@"c:\file.txt", Encoding.UTF8))
{
    // process the line
}

Read Text File Line by Line (with StreamReader)

The code above can be implement also directly using StreamReader.Re­adLine as shows the code bellow.

[C#]
var fileStream = new FileStream(@"c:\file.txt", FileMode.Open, FileAccess.Read);
using (var streamReader = new StreamReader(fileStream, Encoding.UTF8))
{
    string line;
    while ((line = streamReader.ReadLine()) != null)
    {
        // process the line
    }
}

Files and Folders Examples


See also

By Jan Slama, 2015