Skip to main content

StreamReader

StreamReader class

In my previous article we have have seen how to read from text file using File class and how to write into text file using StreamWriter class. In this article we will see how to read from text file using StreamReader  class.

Using Statements: It is recommended to use using statements while we are using StreamReader class, which ensures that is is removed from the memory once it is no longer needed. The syntax is very easy to use.
StreamReader class reads text file, it is available in System.IO namespace. It provides very good performance. Using StreamReader we can read a file synchronously and asynchronously, we need to provide a relative or absolute path to the file.

Lets check with the example that how to synchronously read a line from text file using StreamReader class. First we need to declare and initialize an instance of StreamReader class with using statement.
Example 1

using System;
using System.IO;

class Program
{
    static void Main(string[] args)
    {
        string line;
        using (StreamReader reader = new StreamReader(@"C:\Users\Tarun\Documents\File1.txt"))
        {
            line = reader.ReadLine();
        }
        Console.WriteLine(line);
        Console.Read();
    }
}

Example 2
Now lets check with the example that how to read all the line from a text file using StreamReader class.

using System;
using System.IO;

class Program
{
    static void Main(string[] args)
    {
        using (StreamReader reader = new StreamReader(@"C:\Users\Tarun\Documents\File1.txt"))
        {
            while (true)
            {
                string line = reader.ReadLine();
                if (line == null)
                {
                    break;
                }
                Console.WriteLine(line); // Use line.
            }
            Console.Read();
        }
    }
}

In the above example we have used a while loop to read all the line 1 by 1. If we don’t want to use while loop to read whole file then we can also use reader.ReadToEnd() method which will read the content of a text file to the end.

Scope : Scope is a code block between curly braces. Scope allows compiler to make some assumption about the program when some code is unreachable. So garbage collector can reclaimed the program’s memory.

See the below output for example 2

streamreader
streamreader

We have see the synchronous read operation in above both example, now let’s see asynchronous read operation.
asynchronous we need to make async method and have to use await keyword before calling a method.

see the example below.

private async void ReadFileButton_Click(object sender, EventArgs e)
{
    string textFileOutPut = string.Empty;
    try
    {
        using (StreamReader reader = new StreamReader(@"C:\Users\Tarun\Documents\File1.txt"))
        {
            String line = await reader.ReadToEndAsync();
            textFileOutPut = line;
        }
    }
    catch (Exception ex)
    {
        textFileOutPut = "Could not read the file, " + ex.Message;
    }
}

We have created a winform application and put a button called ReadFileButton, and on click event (which we made async) ReadToEndAsync() with await keyword so it will read the given file asynchronously.

Note : With the using statement and StreamReader class we have read a text file. It is a excellent class and useful for many C# programmers.
Download the whole working code here.

 

Understanding StreamWriter class

We have seen how to write in text file using File class in our previous article. Today we will see how to use StreamWriter class to write in a text file.
This class is very helpful to write text data into files. This class contains method to write to a file synchronously like Write and WriteLine or asynchronously WriteAsync and WriteLineAsync.
Using Statements. It is recommended to use using statements while we are using Stream Writer class, which ensures that is is removed from the memory once it is no longer needed. The syntax is very easy to use.
Lets check with the example that how to synchronously write to a text file using Stream Writer class. First we need to declare and initialize an instance of the class with using statement. It is available is available in System.IO namespace

Example 1

using System;
using System.IO;

class Program
{
    static void Main()
    {
        using (StreamWriter writer = new StreamWriter(@"C:\Users\Tarun\Documents\File1.txt"))
        {
            writer.Write("First Word");
            writer.WriteLine("Second Word");
            writer.WriteLine("Third Line to write into the text file.");
            writer.Close();
            Console.ReadLine();
        }
    }
}

Example 2
Now lets check with the example that how to asynchronously write to a text file.

using System;
using System.IO;

class Program
{
    static void Main()
    {
        using (StreamWriter writerAsync = new StreamWriter(@"C:\Users\Tarun\Documents\AsyncFile1.txt"))
        {
            writerAsync.WriteAsync("First Word");
            writerAsync.WriteLineAsync("Second Word");
            writerAsync.WriteLineAsync("Third Line to write into the text file.");
            writerAsync.Close();
            Console.ReadLine();
        }

    }
}

See the below output for both example

StreamWriter class output
StreamWriter class output

Note : With the using statement and Stream Writer class we have written a text file. It is a excellent class and useful for many C# programmers.
Download the whole working code here.

How to Read from a Text File using C#

In previous article we have see “How to write to a Text File using C#“, Now in this article we are going to learn how can we read text file using C#. In most of the application either we are writing something to text file or reading from text file. Reading from and writing to text file is essential for major application. So lets see the code for reading text file using C#.

The main important class is File for Read from text file which exists in System.IO namespace.
So first we need to import System.IO namespace to our project.

Now lets see example for ReadAllText method

ReadAllText

ReadAllText method will read all the content of a given file. It will take 1 parameter as a full file path.

Example #1

using System;
using System.IO;

namespace ReadFromTextFile
{
class Program
{
static void Main(string[] args)
{
string pathToReadFile = @"C:\Users\Public\";

// Example #1
// Read the file as one string.
string textFromFile = File.ReadAllText(pathToReadFile +"File1.txt");
Console.WriteLine(textFromFile);
Console.ReadKey();

}
}
}

ReadAllLines

ReadAllLines method will read all the lines of a given file in an array. It will also take 1 parameter as a full file path.

Example #2

using System;
using System.IO;

namespace ReadFromTextFile
{
class Program
{
static void Main(string[] args)
{
string pathToReadFile = @"C:\Users\Public\";

// Example #1
// Read the file as one string.
string textFromFile = File.ReadAllText(pathToReadFile +"File1.txt");
Console.WriteLine(textFromFile);

string[] linesOfText = File.ReadAllLines(pathToReadFile + "File2.txt");

foreach (string singleLine in linesOfText)
{
// print each line on a different line.
Console.WriteLine("\n" + singleLine);
}

//Lets system wait until user press any key to see the result on a console window
Console.ReadKey();
}
}
}

Please change path of “pathToReadFile” variable if that path does not exists on your system, also change the name of txt file.
If file path doesn’t exist on your system then it may cause an exception

You can download an example here.