Easy Tutorial
❮ Csharp Delegate Csharp Switch ❯

C# Reading and Writing Text Files

C# File Input and Output

StreamReader and StreamWriter classes are used for reading and writing data to text files. These classes inherit from the abstract base class Stream, which supports reading and writing bytes in file streams.

StreamReader Class

The StreamReader class inherits from the abstract base class TextReader, which represents a reader that reads a sequence of characters.

The following table lists some commonly used methods in the StreamReader class:

No. Method & Description
1 public override void Close() <br> Closes the StreamReader object and the underlying stream, and releases any system resources associated with the reader.
2 public override int Peek() <br> Returns the next available character but does not consume it.
3 public override int Read() <br> Reads the next character from the input stream and advances the character position by one character.

For a complete list of methods, visit Microsoft's C# documentation.

Example

The following example demonstrates reading a file named Jamaica.txt. The file content is as follows:

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 a StreamReader instance to read the 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)
            {
                // Display an error message to the user
                Console.WriteLine("The file could not be read:");
                Console.WriteLine(e.Message);
            }
            Console.ReadKey();
        }
    }
}

When you compile and run the above program, it will display the contents of the file.

StreamWriter Class

The StreamWriter class inherits from the abstract class TextWriter, which represents a writer that writes a sequence of characters.

The following table lists some commonly used methods in the StreamWriter class:

No. Method & Description
1 public override void Close() <br> Closes the current StreamWriter object and the underlying stream.
2 public override void Flush() <br> Clears all buffers for the current writer and causes any buffered data to be written to the underlying stream.
3 public virtual void Write(bool value) <br> Writes the text representation of a Boolean value to the text string or stream. (Inherited from TextWriter.)
4 public override void Write(<br> char value<br>) <br> Writes a character to the stream.
5 public virtual void Write(<br> decimal value<br>) <br>Writes the text representation of a decimal value to the text string or stream.
6 public virtual void Write(<br> double value<br>) <br>Writes the text representation of an 8-byte floating-point value to the text string or stream.
7 public virtual void Write(<br> int value<br>) <br>Writes the text representation of a 4-byte signed integer to the text string or stream.
8 public override void Write(<br> string value<br>) <br>Writes a string to the stream.
9 public virtual void WriteLine() <br>Writes a line terminator to the text string or stream.

For the complete list of methods, please visit Microsoft's C# documentation.

Example

The following example demonstrates using the StreamWriter class to write text data to a file:

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 display 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

C# File Input and Output

❮ Csharp Delegate Csharp Switch ❯