StreamReader and StreamWriter in C Sharp (C#) - Time & Space Complexity
Start learning this pattern below
Jump into concepts and practice - no test required
When working with files in C#, we often use StreamReader and StreamWriter to read and write text.
We want to understand how the time it takes to read or write grows as the file size grows.
Analyze the time complexity of the following code snippet.
using System.IO;
void WriteLines(string filePath, string[] lines)
{
using var writer = new StreamWriter(filePath);
foreach (var line in lines)
{
writer.WriteLine(line);
}
}
This code writes each string from an array to a file line by line.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The foreach loop writes each line to the file.
- How many times: It runs once for every line in the input array.
As the number of lines grows, the time to write grows roughly the same amount.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 write calls |
| 100 | About 100 write calls |
| 1000 | About 1000 write calls |
Pattern observation: The time grows in a straight line with the number of lines.
Time Complexity: O(n)
This means the time to write grows directly with the number of lines you write.
[X] Wrong: "Writing to a file is instant and does not depend on the number of lines."
[OK] Correct: Each line requires a write operation, so more lines mean more work and more time.
Understanding how file reading and writing scales helps you write efficient programs and answer questions about performance clearly.
"What if we read the file line by line using StreamReader instead of writing? How would the time complexity change?"
Practice
StreamReader class in C#?Solution
Step 1: Understand StreamReader's role
StreamReaderis designed to read text data from files.Step 2: Differentiate from StreamWriter
StreamWriterwrites text, not reads it.Final Answer:
To read text from a file -> Option AQuick Check:
StreamReader reads files = D [OK]
- Confusing StreamReader with StreamWriter
- Thinking StreamReader creates files
- Assuming StreamReader deletes files
StreamWriter in C#?Solution
Step 1: Recognize correct StreamWriter instantiation
The correct way is to usenew StreamWriter("file.txt")inside ausingblock for safe disposal.Step 2: Check syntax correctness
using (StreamWriter writer = new StreamWriter("file.txt")) { } usesusingwith proper syntax and constructor call.Final Answer:
using (StreamWriter writer = new StreamWriter("file.txt")) { } -> Option BQuick Check:
Correct StreamWriter syntax = B [OK]
- Missing 'new' keyword
- Not using 'using' block for disposal
- Incorrect method calls like .read() on StreamWriter
using (var writer = new StreamWriter("test.txt")) {
writer.WriteLine("Hello");
writer.WriteLine("World");
}
using (var reader = new StreamReader("test.txt")) {
string content = reader.ReadToEnd();
Console.Write(content);
}Solution
Step 1: Understand StreamWriter.WriteLine behavior
Each WriteLine writes the string plus a newline character at the end.Step 2: ReadToEnd reads full content including newlines
The reader reads the entire file content, preserving newlines.Final Answer:
Hello\nWorld\n -> Option CQuick Check:
WriteLine adds newline, ReadToEnd reads all [OK]
- Ignoring newline characters added by WriteLine
- Assuming WriteLine writes without newlines
- Confusing output formatting in Console.Write
StreamReader reader = new StreamReader("data.txt");
string line = reader.ReadLine();
Console.WriteLine(line);
reader.Close();Solution
Step 1: Check resource management
The code opens a StreamReader but does not use ausingblock, risking resource leaks if exceptions occur.Step 2: Confirm method correctness
ReadLine()is correct to read one line;Close()is called but manual closing is less safe thanusing.Final Answer:
Missing 'using' block to ensure file closure -> Option AQuick Check:
Use 'using' to auto-close files [OK]
- Not using 'using' block for automatic disposal
- Confusing ReadLine with ReadAll
- Calling Close before reading
StreamReader and StreamWriter. Which code snippet correctly performs this task?Solution
Step 1: Check proper resource management
using (var reader = new StreamReader("source.txt")) { using (var writer = new StreamWriter("dest.txt")) { string line; while ((line = reader.ReadLine()) != null) { writer.WriteLine(line); } } } uses nestedusingblocks to ensure both reader and writer are properly closed.Step 2: Verify reading and writing logic
It reads line by line until null, writing each line to the destination file correctly.Final Answer:
Correct nested using blocks with line-by-line copy -> Option DQuick Check:
Nested using + line loop = A [OK]
- Not disposing writer properly
- Reversing reader and writer order in using blocks
- Not looping to read all lines
- Not disposing writer in option D
