StreamReader and StreamWriter help you read from and write to files easily. They make working with text files simple and organized.
StreamReader and StreamWriter in 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.
using (StreamReader reader = new StreamReader("data.txt")) { string content = reader.ReadToEnd(); Console.WriteLine(content); }
using (StreamWriter writer = new StreamWriter("log.txt")) { writer.WriteLine("Log started"); writer.WriteLine("Another log entry"); }
using (StreamReader reader = new StreamReader("notes.txt")) { string line; while ((line = reader.ReadLine()) != null) { Console.WriteLine(line); } }
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.
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); } } } }
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.
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.