StreamReader and StreamWriter in C#

StreamReader and StreamWriter in C# with Examples

In this article, I am going to discuss StreamReader and StreamWriter in C# with Examples. Please read our previous article where we discussed FileStream Class in C# with Examples. At the end of this article, you will understand what StreamReader and StreamWriter are in C# and when and how to use StreamReader and StreamWriter in C# with Examples.

StreamWriter Class in C#

The StreamWriter class in C# is more popular in File Handling and it is very helpful in writing text data in the file. It is easy to use and provides a complete set of constructors and methods to work.

If you go to the definition of StreamWriter class then you will see the following. The StreamWriter class in C# belongs to the System.IO namespace and implements the abstract TextWriter class. StreamWriter class in C# is used for writing characters to stream in a particular format.

StreamWriter Class in C#

As you can see in the above image, this class contains lots of methods, different types of constructors, and a few properties.

Constructor:

StreamWriter(): The Constructor is used to initialize a new instance of the System.IO.StreamWriter class for the specified. It has also different overloaded versions for different ways to create an instance of StreamWriter class.

Methods:
  1. Close(): This method closes the current StreamWriter object and the underlying stream.
  2. Flush(): This method Clears data from all buffers for the current writer and causes any buffered data to be written to the underlying stream.
  3. Write(): It Writes data to the stream. It has different overloads for different data types to write in the stream.
  4. WriteLine: It is the same as Write() but it adds the newline character at the end of the data. It has different overloads for different data types to write in the stream.
  5. Dispose(): It releases the unmanaged resources used by the StreamWriter and optionally releases the managed resources.
Properties:
  1. AutoFlush: Gets or sets a value indicating whether the StreamWriter will flush its buffer to the underlying stream after every call to System.IO.StreamWriter.Write(System.Char).
  2. BaseStream: Gets the underlying stream that interfaces with a backing store.
  3. Encoding: Gets the System.Text.Encoding in which the output is written.
Example to write user input to a file using StreamWriter Class in C#:

It is very easy to write data into a text file using StreamWriter Class and most beginners prefer to use this class in writing files.

In the below example, we are using the StreamWriter constructor version (public StreamWriter(string path);) which takes the string path as an argument to create an instance of StreamWriter class. This StreamWriter instance will create a file with the name MyFile.txt at the specified location i.e. in the D Drive. Using the Console.ReadLine() method we are taking the input data from the user which we will store in our MyFile.txt file. When we call the Write method passing the string data, it will write the string data into the stream i.e. into the text file. Finally, we call the Flush and Close method to clear all the buffers as well as close the stream.

using System;
using System.IO;
namespace FileHandlinDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            // This will create a file named MyFile.txt at the specified location i.e. in the D Drive
            // Here we are using the StreamWriter constructor which takes the string path as an argument to create an instance of StreamWriter class
            StreamWriter sw = new StreamWriter("D://MyFile.txt");

            //Asking user to enter the text that we want to write into the MyFile.txt file
            Console.WriteLine("Enter the Text that you want to write on File");

            // To read the input from the user
            string str = Console.ReadLine();

            // To write the data into the stream
            sw.Write(str);

            // Clears all the buffers
            sw.Flush();

            // To close the stream
            sw.Close();
            Console.ReadKey();
        }
    }
}
Output:

Example to write user input to a file using StreamWriter Class in C#

Now, you will see that, it will create a text file with the name MyFile.txt in the D drive and once you open the file you will see the following data written inside it.

StreamReader and StreamWriter in C# with Examples

Save Variable Data to File in C# using StreamWriter Class

Several times you need to save variable data in a file. These variable data might be the output of our program, log details, exceptions, errors, etc. Now, let us see, how can we can save variable data in a file using StreamWriter Class.

using System;
using System.IO;

namespace FileHandlinDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            string file = @"D:\MyTextFile1.txt";
            int a, b, result;
            a = 15;
            b = 20;
            result = a + b;

            using (StreamWriter writer = new StreamWriter(file))
            {
                writer.Write("Sum of {0} + {1} = {2}", a, b, result);
            }
            Console.WriteLine("Saved");
            Console.ReadKey();
        }
    }
}

Now open the D:\MyTextFile1.txt file and you will see the following text.

Sum of 15 + 20 = 25

StreamReader Class in C#

The StreamReader class in C# allows us to read text files easily. Its implementation is easy and it is widely popular among the developers. However, there are many ways to read text files in C# but StreamReader Class is more popular in the list. While working with C# StreamReader Class, you need to remember the following points.

  1. Implements a TextReader that reads characters from a byte stream in a particular encoding.
  2. StreamReader class uses UTF-8 Encoding by defaults.
  3. StreamReader class is designed for character input in a particular encoding.
  4. Use this class for reading a standard text file.
  5. By default, it is not thread-safe.

If you go to the definition of StreamReader class then you will see the following. The StreamReader class belongs to the System.IO namespace and implements the abstract TextReader class. The StreamReader class in C# is used for reading characters from the stream in a particular format.

StreamReader Class in C#

As you can see in the above image, the StreamReader class contains lots of methods, different types of constructors, and a few properties.

Constructor:

StreamReader(): It initializes a new instance of the StreamReader class for the specified stream. It has different overloaded versions.

Methods:
  1. Close(): The Close method Closes the StreamReader object and the underlying stream, and releases any system resources associated with the reader.
  2. Peek(): This method returns the next available character but does not consume it. An integer represents the next character to be read, or -1 if there are no characters to be read or if the stream does not support seeking.
  3. Read(): This method reads the next character from the input stream and advances the character position by one character. The next character from the input stream is represented as a System.Int32 object, or -1 if no more characters are available.
  4. ReadLine(): This method Reads a line of characters from the current stream and returns the data as a string. The next line from the input stream, or null if the end of the input stream is reached.
  5. Seek(): It is used to read/write at a specific location from a file.
Properties:
  1. CurrentEncoding: It gets the current character encoding that the current System.IO.StreamReader object is using.
  2. EndOfStream: It gets a value that indicates whether the current stream position is at the end of the stream.
  3. BaseStream: It returns the underlying stream.
Example to read from a file using StreamReader Class in C#:
using System;
using System.IO;
namespace FileHandlinDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            //Creating a new input stream i.e.  MyFile.txt and opens it
            StreamReader sr = new StreamReader("D://MyFile.txt");

            Console.WriteLine("Content of the File");

            // This is used to specify from where to start reading input stream
            sr.BaseStream.Seek(0, SeekOrigin.Begin);

            // To read line from input stream
            string str = sr.ReadLine();

            // To read the whole file line by line
            while (str != null)
            {
                Console.WriteLine(str);
                str = sr.ReadLine();
            }
            Console.ReadLine();

            // to close the stream
            sr.Close();
            Console.ReadKey();
        }
    }
}
Output:

Example to read from a file using StreamReader Class in C#

StreamReader and StreamWriter class Example in C#

As discussed, it is very easy to read a text file using StreamReader Class. In the below example, we are doing the following thing:

  • Write some data on a text file using StreamWriter class
  • Read those data using StreamReader class.
Example:
using System;
using System.IO;

namespace FileHandlinDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            string file = @"D:\MyTextFile2.txt";

            //Writer data to text file
            using (StreamWriter streamWriter = new StreamWriter(file))
            {
                streamWriter.WriteLine("Hellow StreamWriter Class in C#");
                streamWriter.WriteLine("How are you Doing?");
            }

            //Reading text file using StreamReader Class            
            using (StreamReader reader = new StreamReader(file))
            {
                Console.WriteLine(reader.ReadToEnd());
            }
            Console.ReadKey();
        }
    }
}
Output:

StreamReader and StreamWriter class Example in C#

In the next article, I am going to discuss File Class in C# with Examples. Here, in this article, I try to explain StreamReader and StreamWriter in C# with examples. I hope you enjoy this StreamReader and StreamWriter in C# with Examples article. I would like to have your feedback. Please post your feedback, question, or comments about this article.

Leave a Reply

Your email address will not be published.