C# - StreamReader And StreamWriter Class

StreamReader And StreamWriter Class

StreamReader and StreamWriter classes are used when we dealing with text files.StreamReader is derived from the TextReader class, an abstract class that represents a reader that can read a sequential series of characters.

The following code snippet uses the StreamReader class to read lines from a text file:

try
{
    using (StreamReader sr = new StreamReader(filePath))
    {
        string line;
        while ((line = sr.ReadLine()) != null)
        {
                Console.WriteLine(line);
        }
    }
}
catch (Exception ex)
{
         Console.WriteLine(ex.ToString());
}           

In addition to the ReadLine() method, the StreamReader class supports the following methods:

  • Read() — Reads the next character from the input stream
  • ReadBlock() — Reads a maximum of specified characters
  • ReadToEnd() — Reads from the current position to the end of the stream

The StreamWriter class is derived from the abstract TextWriter class and is used for writing characters to a stream. The following code snippet uses the StreamWriter class to write lines to a text file:

try
{
    using (StreamWriter sw = new StreamWriter(filePath))
    {
        sw.Write("Hello, ");
        sw.WriteLine("World!");
    }
}
catch (Exception ex)
{
    Console.WriteLine(ex.ToString());
}