0
0
C Sharp (C#)programming~5 mins

StreamReader and StreamWriter in C Sharp (C#)

Choose your learning style9 modes available
Introduction

StreamReader and StreamWriter help you read from and write to files easily. They make working with text files simple and organized.

You want to save user input into a text file.
You need to read configuration settings from a file.
You want to log messages or errors to a file.
You need to process data stored in a text file line by line.
Syntax
C Sharp (C#)
using System.IO;

// To read from a file
using (StreamReader reader = new StreamReader("filename.txt"))
{
    string line = reader.ReadLine();
}

// To write to a file
using (StreamWriter writer = new StreamWriter("filename.txt"))
{
    writer.WriteLine("text to write");
}

Always use using to automatically close the file after reading or writing.

StreamReader reads text line by line or all at once, StreamWriter writes text line by line or all at once.

Examples
This reads the entire file content at once and prints it.
C Sharp (C#)
using (StreamReader reader = new StreamReader("data.txt"))
{
    string content = reader.ReadToEnd();
    Console.WriteLine(content);
}
This writes two lines to the file named "log.txt".
C Sharp (C#)
using (StreamWriter writer = new StreamWriter("log.txt"))
{
    writer.WriteLine("Log started");
    writer.WriteLine("Another log entry");
}
This reads the file line by line and prints each line.
C Sharp (C#)
using (StreamReader reader = new StreamReader("notes.txt"))
{
    string line;
    while ((line = reader.ReadLine()) != null)
    {
        Console.WriteLine(line);
    }
}
Sample Program

This program writes two lines to a file named "example.txt" and then reads the file line by line, printing each line to the console.

C Sharp (C#)
using System;
using System.IO;

class Program
{
    static void Main()
    {
        string fileName = "example.txt";

        // Write some lines to the file
        using (StreamWriter writer = new StreamWriter(fileName))
        {
            writer.WriteLine("Hello, world!");
            writer.WriteLine("Welcome to StreamWriter.");
        }

        // Read and print the file content
        using (StreamReader reader = new StreamReader(fileName))
        {
            string line;
            while ((line = reader.ReadLine()) != null)
            {
                Console.WriteLine(line);
            }
        }
    }
}
OutputSuccess
Important Notes

If the file does not exist, StreamWriter will create it automatically.

StreamReader throws an error if the file does not exist, so make sure the file is there before reading.

Always close or dispose StreamReader and StreamWriter to free system resources; using using does this automatically.

Summary

StreamReader reads text from files easily, line by line or all at once.

StreamWriter writes text to files, creating or overwriting them.

Use using blocks to handle files safely and cleanly.