Letβs go through reading and writing text files in C# using StreamReader and StreamWriter β the standard way to handle text files.
π 1. StreamWriter: Writing Text Files
-
StreamWriteris used to write text to a file -
Can create a new file or overwrite/append to an existing file
Basic Syntax
using System.IO;
string path = "example.txt";
using (StreamWriter writer = new StreamWriter(path))
{
writer.WriteLine("Hello, World!");
writer.WriteLine("This is a text file.");
}-
usingensures the file is properly closed after writing -
WriteLinewrites a line with newline,Writewrites without newline
Append Mode
using (StreamWriter writer = new StreamWriter(path, append: true))
{
writer.WriteLine("Adding a new line.");
}π 2. StreamReader: Reading Text Files
-
StreamReaderis used to read text from a file -
Can read line by line or the entire file
Read Entire File
using (StreamReader reader = new StreamReader(path))
{
string content = reader.ReadToEnd();
Console.WriteLine(content);
}Read Line by Line
using (StreamReader reader = new StreamReader(path))
{
string line;
while ((line = reader.ReadLine()) != null)
{
Console.WriteLine(line);
}
}π 3. File.Exists Check
- Always good practice to check if file exists before reading:
if (File.Exists(path))
{
using (StreamReader reader = new StreamReader(path))
{
Console.WriteLine(reader.ReadToEnd());
}
}
else
{
Console.WriteLine("File not found!");
}π 4. Other Useful Methods
| Method / Class | Purpose |
|---|---|
File.ReadAllText() | Reads entire file in one call |
File.ReadAllLines() | Reads all lines into a string array |
File.WriteAllText() | Writes entire string to file (overwrites) |
File.AppendAllText() | Appends text to a file |
π 5. Example: Writing & Reading Together
string filePath = "data.txt";
// Write to file
using (StreamWriter writer = new StreamWriter(filePath))
{
writer.WriteLine("Alice,25");
writer.WriteLine("Bob,30");
}
// Read from file
using (StreamReader reader = new StreamReader(filePath))
{
string line;
while ((line = reader.ReadLine()) != null)
{
string[] parts = line.Split(',');
Console.WriteLine($"Name: {parts[0]}, Age: {parts[1]}");
}
}Output:
Name: Alice, Age: 25
Name: Bob, Age: 30
π 6. Best Practices
-
Use
usingblocks to automatically close streams -
Handle exceptions (e.g.,
FileNotFoundException,IOException) -
Use File.Exists before reading
-
Prefer File.ReadAllText / WriteAllText for small files for simplicity
β Tip:
-
Use StreamReader/StreamWriter for large files where line-by-line processing is needed
-
Use File.ReadAllText / WriteAllText for small files