Ebooks

C# StreamReader tutorial

C# StreamReader tutorial shows how to read text files in C# with StreamReader. C# tutorial is a comprehensive tutorial on C# language.

Input & output in C# is based on streams. A Stream is an abstract base class of all streams. A stream is an abstraction of a sequence of bytes, such as a file, an input/output device, an inter-process communication pipe, or a TCP/IP socket.

C# StreamReader

StreamReader reads characters from a byte stream in a particular encoding. It is a convenience class for working with text data instead of bytes. StreamReader defaults to UTF-8 encoding unless specified otherwise.

thermopylae.txt
The Battle of Thermopylae was fought between an alliance of Greek city-states, 
led by King Leonidas of Sparta, and the Persian Empire of Xerxes I over the 
course of three days, during the second Persian invasion of Greece. 

In our examples, we are going to read from this file.

C# StreamReader ReadToEnd

The ReadToEnd() method reads all characters from the current position to the end of the stream. It returns the rest of the stream as a string, from the current position to the end; if the current position is at the end of the stream, it returns an empty string.

Note: This method is not suited for large files. If the file had 8 GB, it would load all the data into the memory.

Program.cs
using System;
using System.IO;

namespace ReadToEndEx
{
    class Program
    {
        static void Main(string[] args)
        {
            var fileName = @"C:\Users\Jano\Documents\thermopylae.txt";

            using var sr = new StreamReader(fileName);

            string content = sr.ReadToEnd();
            Console.WriteLine(content);
        }
    }
}

The example reads a file into a string in one shot.

var fileName = @"C:\Users\Jano\Documents\thermopylae.txt";

We define the filename.

using var sr = new StreamReader(fileName);

A new StreamReader is created. The using keyword releases the IO resources when the sr variable goes out of scope.

string content = sr.ReadToEnd();
Console.WriteLine(content);

We read the contents of the file with ReadToEnd() and print them to the console.

$ dotnet run
The Battle of Thermopylae was fought between an alliance of Greek city-states,
led by King Leonidas of Sparta, and the Persian Empire of Xerxes I over the
course of three days, during the second Persian invasion of Greece.

This is the output.

C# StreamReader ReadBlock

The ReadBlock() method reads the specified maximum number of characters from the current stream and writes the data to a buffer, beginning at the specified index. It returns the number of characters that have been read.

Program.cs
using System;
using System.IO;

namespace ReadBlockEx
{
    class Program
    {
        static void Main(string[] args)
        {
           var fileName = @"C:\Users\Jano\Documents\thermopylae.txt";

            using var sr = new StreamReader(fileName);

            char[] buf = new char[25];

            int n = sr.ReadBlock(buf, 0, buf.Length);

            Console.WriteLine($"{n} characters read");
            Console.WriteLine(buf);
        }
    }
}

The example reads the first twenty-five characters from the file.

char[] buf = new char[25];

We define the character buffer.

int c = sr.ReadBlock(buf, 0, buf.Length);

We read characters from the file with the ReadBlock() method. We start from the first character and specify the length of the array as the number of characters to be read.

Console.WriteLine($"{n} characters read");

We print the number of characters read.

Console.WriteLine(buf); 

We print the character array content.

$ dotnet run
25 characters read
The Battle of Thermopylae

This is the output.

C# StreamReader ReadLine

The ReadLine method reads a line of characters from the current stream and returns the data as a string. It returns null if the end of the input stream is reached.

Program.cs
using System;
using System.IO;

namespace ReadLineEx
{
    class Program
    {
        static void Main(string[] args)
        {
            var fileName = @"C:\Users\Jano\Documents\thermopylae.txt";

            using var sr = new StreamReader(fileName);

            string line;

            while ((line = sr.ReadLine()) != null)
            {
                Console.WriteLine(line);
            }
        }
    }
}

The example reads the whole file line by line by using the ReadLine() method.

string line;

while ((line = sr.ReadLine()) != null)
{
    Console.WriteLine(line);
}

We use a while loop to read all lines.

C# StreamReader read web page

In the following example, we read HTML data from a web page.

Program.cs
using System;
using System.IO;
using System.Net.Http;
using System.Threading.Tasks;

namespace ReadWebPageEx
{
    class Program
    {
        static async Task Main(string[] args)
        {
            using var httpClient = new HttpClient();
            var url = "http://webcode.me";

            var stream = await httpClient.GetStreamAsync(url);

            using var sr = new StreamReader(stream);

            string content = sr.ReadToEnd();
            Console.WriteLine(content);
        }
    }
}

The example reads the home page of a website; it uses the HttpClient. HttpClient sends HTTP requests and receives HTTP responses from a resource identified by a URL.

using var httpClient = new HttpClient();
var url = "http://webcode.me";

An HttpClient and the URL are created.

using var sr = new StreamReader(stream);

The StreamReader can take streams as argument as well.

var stream = await httpClient.GetStreamAsync(url);

We asynchronously read from the URL.

string content = sr.ReadToEnd();
Console.WriteLine(content);

We read the whole page and print the HTML data to the console.

$ dotnet run
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>My html page</title>
</head>
<body>

    <p>
        Today is a beautiful day. We go swimming and fishing.
    </p>

    <p>
         Hello there. How are you?
    </p>

</body>
</html>

This is the output.

In this tutorial we have read text files in C# with StreamReader.

Read C# tutorial or list all C# tutorials.