C# FileStream, StreamWriter, StreamReader, TextWriter, TextReader

By Sruthy

By Sruthy

Sruthy, with her 10+ years of experience, is a dynamic professional who seamlessly blends her creative soul with technical prowess. With a Technical Degree in Graphics Design and Communications and a Bachelor’s Degree in Electronics and Communication, she brings a unique combination of artistic flair…

Learn about our editorial policies.
Updated March 7, 2024

In this Tutorial, You will Learn about System.IO which is a C# Namespace. This Namespace Provides C# Classes such as FileStream, StreamWriter, StreamReader To Handle File I/O:

A file is basically a system object stored in the memory at a particular given directory with a proper name and extension. In C#, we call a file as stream if we use it for writing or reading data.

In this tutorial, we will look into both input stream which is used to retrieve data from a given file and output stream that is used to put data into a file.

=> Check For Our Ultimate C# Training Guide Here


C# FileStream For File I/O

System.IO Namespace

System.IO is a namespace present in the C# that contains classes that can be used for carrying out different operations on a given stream like creating, editing and retrieving data from a given file.

Let us have a look at some of these classes.

C# FileStream

File stream offers a path for performing file operations. It is mainly used for reading and writing data into the files.

Example to write into a file:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace ConsoleApp1
{
class Program
     {
              static void Main(string[] args)
             {
            
                  FileStream f = new FileStream("d:\\b.txt", FileMode.OpenOrCreate);

                 Console.WriteLine("File opened");
            
                  f.WriteByte(70);
                 Console.WriteLine("Data written into file");
            
                 f.Close();
                 Console.WriteLine("File Stream closed");
            }
       } 
}

Here, we wrote a simple program to write a single byte data into the file using file stream. At first, we created a FileStream object and passed the name of the file. Then we set the file mode to open or create. In the opened file, we wrote a single byte using WriteByte and at last, we closed everything.

The output is a txt file with a single byte.

FileStream output

Example to Read a file

In our previous example we learned how to write into a file now, let’s try to read the file.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace ConsoleApp1
{
class Program
       {
static void Main(string[] args)
               {
            
FileStream f = new FileStream("d:\\b.txt", FileMode.OpenOrCreate);
            
Console.WriteLine("File opened");
            
char a = (char)f.ReadByte();
            
Console.WriteLine("Data read from file is: "+a);
            
f.Close();
            
Console.WriteLine("File Stream closed");
            
Console.ReadLine();
                 }
        }
}

Here we have used ReadByte to read the byte from the file. This command is used to read a single byte from the file. If you want to read more data you will need to pass it through a loop. We then stored it into a char variable but as the return type will not always match for ReadByte, we have also added a cast for char.

If we run this program, the following output is observed.

Output

File opened
Data read from file is: F
File Stream closed

C# StreamWriter

The StreamWriter class in C# is used for writing characters to a stream. It uses the TextWriter class as a base class and provides the overload methods for writing data into a file.

The StreamWriter is mainly used for writing multiple characters of data into a file.

Example:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;

namespace ConsoleApp1
{
class Program
       {
static void Main(string[] args)
               {
            
FileStream f = new FileStream("d:\\b.txt", FileMode.OpenOrCreate);
            
Console.WriteLine("File opened");
            
//declared stream writer
StreamWriter s = new StreamWriter(f);
           
Console.WriteLine("Writing data to file");
            
s.WriteLine("Writing data into file using stream writer");
            
//closing stream writer
s.Close();
f.Close();
            
Console.WriteLine("File Stream closed");
            
Console.ReadLine();
                 }
        }
}

After initializing the FileStream object, we also initialized the StreamWriter object using the FileStream object. Then we used the WriteLine method to write a single line of data into the file. We then closed the StreamWriter and then the FileStream.

The output of the following code will be a file with user data written in it.

Output

StreamWriter output

C# StreamReader

The StreamReader is used for reading string or large sentences from a file. The StreamReader also uses the TextReader class as its base class and then offers methods like Reading and ReadLine to read data from the stream.

Example of Reading data:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace ConsoleApp1
{
class Program
       {
static void Main(string[] args)
             {
            
FileStream f = new FileStream("d:\\b.txt", FileMode.OpenOrCreate);
            
Console.WriteLine("File opened");
            
//declared stream reader
StreamReader sr = new StreamReader(f);
Console.WriteLine("Reading data from the file");
            
string line = sr.ReadLine();
            
Console.WriteLine("The data from the file is : " + line);
            
//closing stream writer
sr.Close();
f.Close();
            
Console.WriteLine("File Stream closed");
            
Console.ReadLine();
                 }
       }
}

Here we have created an object from the StreamReader using the FileStream. Then we used a simple readline method to read data from the file. We closed the StreamReader and then the FileStream.

The above program produced the following output:

Output:

File opened
Reading data from the file
The data from the file is: Writing data into file using stream writer
File Stream closed

C# TextWriter

In C# the TextWriter class is written as an abstract class. It is used to create a sequential series of characters inside a file. It is quite similar to the stream writer that also allows the user to write sequential characters or text in a file but it doesn’t require FileStream creation for the operation.

Example to know how TextWriter works:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace ConsoleApp1
{
class Program
      {
static void Main(string[] args)
             {
using (TextWriter writer = File.CreateText("d:\\textFile.txt")) { 
            
writer.WriteLine("The first line with text writer");
                 }
Console.ReadLine();
                }
       }
}

The above code works similar to the StreamWriter. The WriteLine method writes the data inside the file. You can write multiple data in the file by using multiple WriteLine methods inside the using statement block.

The output will create a text file with the user-defined text.

Output:

Text Writer

C# TextReader

Text reader is another class that is found in System.IO. It is used to read text or any sequential character from a given file.

Example:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace ConsoleApp1
{
class Program
       {
static void Main(string[] args)
             {
                 using (TextReader txtR = File.OpenText("d:\\textFile.txt")) {
                
                  String data = txtR.ReadToEnd();
                  Console.WriteLine(data);
                  }
                  Console.ReadLine();
                }
        }
}

In the above program, we have used TextReader to open a file that is kept at a particular location. Then we declared a string variable to store the data of the file. The ReadToEnd method ensures that all the data inside the file has been read. After that, we printed the data to the console.

The output of the above program will be:

The first line with text writer

Conclusion

The System.IO namespace inside C# offers various classes and methods to enable programmers to perform read-write operations on different files. System.IO contains several classes like FileStream, StreamReader, StreamWriter, TextReader, TextWriter etc.

All these classes provide a specific implementation for the read writes operations on the file depending upon the requirement.

Code Sample

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace ConsoleApp1
{
class Program
       {
static void Main(string[] args)
             {
            
FileStream f = new FileStream("d:\\b.txt", FileMode.OpenOrCreate);
            
Console.WriteLine("File opened");
            
f.WriteByte(70);
            
Console.WriteLine("Data written into file");
            
char a = (char)f.ReadByte();
            
Console.WriteLine("Data read from file is: " + a);
            
//declared stream writer
StreamWriter s = new StreamWriter(f);
Console.WriteLine("Writing data to file");
            
s.WriteLine("Writing data into file using stream writer");
            


//declared stream reader
StreamReader sr = new StreamReader(f);
            
Console.WriteLine("Reading data from the file");
            
string line = sr.ReadLine();
            
Console.WriteLine("The data from the file is : " + line);
            
//closing stream 
sr.Close();
            

f.Close();
           
Console.WriteLine("File Stream closed");
            
using (TextWriter writer = File.CreateText("d:\\textFile.txt"))
                        {
writer.WriteLine("The first line with text writer");
            }
using (TextReader txtR = File.OpenText("d:\\textFile.txt")) {
                
                               String data = txtR.ReadToEnd();
Console.WriteLine(data);
                         }
Console.ReadLine();
                }
        }
}

=> Watch The Full C# Training Series Here

Was this helpful?

Thanks for your feedback!

Leave a Comment