Stream in C#: StreamReader & StreamWriter [Example]

โšก Smart Summary

A C# stream is a layer between your application and a file that lets you read or write data in small chunks. Here you will learn how StreamReader and StreamWriter work, with examples and the main stream types.

  • ๐ŸŒŠ What it is: A stream is an intermediate layer between your application and a file.
  • ๐Ÿ“– StreamReader: StreamReader reads text from a file one line or chunk at a time.
  • โœ๏ธ StreamWriter: StreamWriter writes text to a file through a stream.
  • ๐Ÿงฉ Stream types: FileStream, MemoryStream, and BufferedStream all derive from the Stream class.
  • ๐Ÿค– AI help: AI tools like GitHub Copilot generate C# stream code instantly.

C# Stream Reader and Writer

What is C# Stream?

In C# file operations, normally streams are used to read and write to files. A stream is an additional layer created between an application and a file. The stream is used to ensure smooth read and write operations to the file.

Streams are normally used when reading data from large files. By using streams, the data from large files in broken down into small chunks and sent to the stream. These chunks of data can then be read from the application.

The reason for breaking it down into small chunks is because of the performance impact of reading a big file in one shot. If you were to read the data from say, a 100 MB file at one shot, your application could just hang and become unstable. The best approach is then to use streams to break the file down into manageable chunks.

So when a write operation is carried out on file, the data to be written, is first written to the stream. From the stream, the data is then written to the file. The same goes for the read operation. In the read operation, data is first transferred from the file to the stream. The data is then read from the application via the stream. Let’s look at an example of how we can read and write using streams.

Types of Streams in C#

All stream classes in C# derive from the abstract Stream class in the System.IO namespace. Each type targets a different data source but shares the same read and write methods. The most commonly used streams are listed below.

  • FileStream reads from and writes to files on disk, one byte or block at a time.
  • MemoryStream stores data in memory instead of a file, which is useful for temporary buffers.
  • BufferedStream wraps another stream to reduce the number of slow disk or network operations.
  • NetworkStream sends and receives data over a network socket.

For working with text, C# provides the StreamReader and StreamWriter helper classes, which wrap a stream and are covered in the next sections.

Stream Reader

The stream reader is used to read data from a file using streams. The data from the file is first read into the stream. Thereafter the application reads the data from the stream.

For our example, we will assume that we have a file in the D drive called Example.txt. The file will be a simple text file and have 2 lines as shown below

  • Guru99 – .Net
  • Guru99 -C#

For our example, we will create a simple Console application and work with File streams

Let’s look at an example of how we can use streams for reading data from a file. Enter the below code in the program.cs file.

Stream Reader

using System;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DemoApplication
{
  class Tutorial
  {
   static void Main(string[] args)
   {
    String path = @"D:\Example.txt";

    using (StreamReader sr = File.OpenText(path))
    {
     String s = "";

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

Code Explanation:-

  1. First, we are declaring a stream reader object. The stream reader object is used in C# to define a stream from the file to the application. The data will be pushed from the file to the stream whenever data is read from the file. The File.OpenText is used to open the file “Example.txt” in read-only mode. The handler to the file is then sent to the stream reader object.
  2. Next, we are defining a temporary variable ‘s’ which will be used to read all the data from the file.
  3. We then use the stream reader method ReadLine to read each line from the stream buffer. When we perform this operation, each line will be first transferred from the file to the buffer. Then the string line will be transferred from the buffer to the variable ‘s’. We then write the contents of the string ‘s’ to the console.

When the above code is set, and the project is run using Visual Studio, you will get the below output.

Output:-

Stream Reader

From the output, you can see that the Stream Reader read both the lines from the file. Finally, the lines of the string read from the stream were sent to the Console.

Stream Writer

The stream writer is used to write data to a file using streams. The data from the application is first written into the stream. After that the stream writes the data to the file. Let’s look at an example of how we can use streams for writing data from a file. Enter the below code in the program.cs file.

Stream Writer

using System;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DemoApplication
{
  class Tutorial
  {
   static void Main(string[] args)
   {
    String path = @"D:\Example.txt";
    
    using (StreamWriter sr = File.AppendText(path))
    {
     sr.WriteLine("Guru99 - ASP.Net");
     sr.Close();

     Console.WriteLine(File.ReadAllText(path));
    }
    Console.ReadKey();
  }
 }
}

Code Explanation:-

  1. First, we are declaring a stream writer object. The stream writer object is used in C# to define a stream. The stream is then used to write data from the application to the file. The data will be pushed from the application to the stream whenever data needs to be written. The File.AppendText command is used to open the file “Example.txt” in an append mode. The handler to the file is then sent to the stream writer object.
  2. We are using the stream write method Writeline to write the line “Guru99 โ€“ ASP.Net” to the stream. From the stream, the line will then be written to the file.
  3. We then close the stream writer after writing to the file. It’s normally a good practice to close file handlers when the file is no longer required for writing purposes.
  4. Finally, we are reading the contents of the file again and writing it to the console log. This is to check as to whether the line was written to the file.

When the above code is set, and the project is run using Visual Studio, you will get the below output.

Output:-

Stream Writer

From the output, you can see that the line “Guru99 โ€“ ASP.Net” was added to the file successfully. All the 3 lines of text can be seen in the console.

FAQs

A stream is an intermediate layer between an application and a file. It breaks large files into small chunks so data can be read or written without loading the whole file into memory.

StreamReader reads text data from a file through a stream. File.OpenText returns a StreamReader, and its ReadLine method reads the file one line at a time.

StreamWriter writes text data to a file through a stream. File.AppendText returns a StreamWriter, and its WriteLine method sends each line to the file.

Common streams include FileStream for files, MemoryStream for in-memory data, BufferedStream for buffering, and NetworkStream for sockets. All derive from the abstract Stream class.

FileStream reads and writes raw bytes to a file, while StreamReader wraps a stream to read text as characters and lines. StreamReader is easier for text files.

AI assistants like GitHub Copilot autocomplete StreamReader and StreamWriter code, add using blocks for disposal, and generate file-reading loops from a short comment.

Yes. AI-powered tools generate stream read and write methods, suggest buffering for large files, and add using statements so streams are closed safely.

A using statement automatically closes and disposes the stream when the block ends, even if an error occurs. This releases the file handle and prevents resource leaks.

Summarize this post with: