C# - Reading from and Writing to Text Files

The StreamReader and StreamWriter classes are used for reading from and writing data to text files. These classes inherit from the abstract base class Stream, which supports reading and writing bytes into a file stream.
The StreamReader class also inherits from the abstract base class TextReader that represents a reader for reading series of characters. The following table describes some of the commonly used methods of the StreamReader class −
public override void Close()
It closes the StreamReader object and the underlying stream, and releases any system resources associated with the reader.
public override int Peek()
Returns the next available character but does not consume it.
public override int Read()
Reads the next character from the input stream and advances the character position by one.
The following example demonstrates reading a text file named Jamaica.txt. The file reads −
Down the way where the nights are gay
And the sun shines daily on the mountain top
I took a trip on a sailing ship
And when I reached Jamaica
I made a stop

using System;
using System.IO;

namespace FileApplication {
   class Program {
      static void Main(string[] args) {
         try {
            // Create an instance of StreamReader to read from a file.
            // The using statement also closes the StreamReader.
            using (StreamReader sr = new StreamReader("c:/jamaica.txt")) {
               string line;

               // Read and display lines from the file until 
               // the end of the file is reached. 
               while ((line = sr.ReadLine()) != null) {
                  Console.WriteLine(line);
               }
            }
         } catch (Exception e) {
            // Let the user know what went wrong.
            Console.WriteLine("The file could not be read:");
            Console.WriteLine(e.Message);
         }
         Console.ReadKey();
      }
   }
}
Guess what it displays when you compile and run the program!
The StreamWriter class inherits from the abstract class TextWriter that represents a writer, which can write a series of character.
The following table describes the most commonly used methods of this class −
public override void Close()
Closes the current StreamWriter object and the underlying stream.
public override void Flush()
Clears all buffers for the current writer and causes any buffered data to be written to the underlying stream.
public virtual void Write(bool value)
Writes the text representation of a Boolean value to the text string or stream. (Inherited from TextWriter.)
public override void Write(char value)
Writes a character to the stream.
public virtual void Write(decimal value)
Writes the text representation of a decimal value to the text string or stream.
public virtual void Write(double value)
Writes the text representation of an 8-byte floating-point value to the text string or stream.
public virtual void Write(int value)
Writes the text representation of a 4-byte signed integer to the text string or stream.
public override void Write(string value)
Writes a string to the stream.
public virtual void WriteLine()
Writes a line terminator to the text string or stream.
For a complete list of methods, please visit Microsoft's C# documentation.
The following example demonstrates writing text data into a file using the StreamWriter class −
using System;
using System.IO;

namespace FileApplication {
   class Program {
      static void Main(string[] args) {
         string[] names = new string[] {"Zara Ali", "Nuha Ali"};
         
         using (StreamWriter sw = new StreamWriter("names.txt")) {

            foreach (string s in names) {
               sw.WriteLine(s);
            }
         }
         
         // Read and show each line from the file.
         string line = "";
         using (StreamReader sr = new StreamReader("names.txt")) {
            while ((line = sr.ReadLine()) != null) {
               Console.WriteLine(line);
            }
         }
         Console.ReadKey();
      }
   }
}
When the above code is compiled and executed, it produces the following result −
Zara Ali
Nuha Ali


    119 Lectures 
     23.5 hours 

 Raja Biswas

    37 Lectures 
     13 hours 

 Trevoir Williams

    16 Lectures 
     1 hours 

 Peter Jepson

    159 Lectures 
     21.5 hours 

 Ebenezer Ogbu

    193 Lectures 
     17 hours 

 Arnold Higuit

    24 Lectures 
     2.5 hours 

 Eric Frick
 Print
 Add Notes
 Bookmark this page