You need to copy the entire content of "source.txt" to "destination.txt" using StreamReader and StreamWriter. Which of the following code snippets correctly accomplishes this?
hard🚀 Application Q8 of Q15
C Sharp (C#) - File IO
You need to copy the entire content of "source.txt" to "destination.txt" using StreamReader and StreamWriter. Which of the following code snippets correctly accomplishes this?
Avar reader = new StreamReader("source.txt");
var writer = new StreamWriter("destination.txt");
string line = reader.ReadLine();
while(line != null) {
writer.Write(line);
line = reader.ReadLine();
}
reader.Close();
writer.Close();
Busing(var writer = new StreamWriter("destination.txt")) {
using(var reader = new StreamReader("source.txt")) {
string content = reader.ReadToEnd();
writer.Write(content);
}
}
Dusing(var reader = new StreamReader("source.txt")) {
string content = reader.ReadLine();
using(var writer = new StreamWriter("destination.txt")) {
writer.WriteLine(content);
}
}
Step-by-Step Solution
Solution:
Step 1: Reading line by line
using(var reader = new StreamReader("source.txt")) {
using(var writer = new StreamWriter("destination.txt")) {
string line;
while((line = reader.ReadLine()) != null) {
writer.WriteLine(line);
}
}
} reads each line until null, ensuring all lines are copied.
Step 2: Writing line by line
Each line is written with WriteLine preserving line breaks.
Step 3: Using nested using blocks
Proper resource management ensures streams are closed automatically.
Step 4: Analyze other options
using(var writer = new StreamWriter("destination.txt")) {
using(var reader = new StreamReader("source.txt")) {
string content = reader.ReadToEnd();
writer.Write(content);
}
} reverses order but still works; however, it reads entire content at once, which is less memory efficient. var reader = new StreamReader("source.txt");
var writer = new StreamWriter("destination.txt");
string line = reader.ReadLine();
while(line != null) {
writer.Write(line);
line = reader.ReadLine();
}
reader.Close();
writer.Close(); misses using blocks and uses Write instead of WriteLine, losing line breaks. using(var reader = new StreamReader("source.txt")) {
string content = reader.ReadLine();
using(var writer = new StreamWriter("destination.txt")) {
writer.WriteLine(content);
}
} reads only one line.
Final Answer:
using(var reader = new StreamReader("source.txt")) {
using(var writer = new StreamWriter("destination.txt")) {
string line;
while((line = reader.ReadLine()) != null) {
writer.WriteLine(line);
}
}
} correctly copies all lines preserving line breaks and resource management.
Quick Check:
Read and write line by line with using [OK]
Quick Trick:Use nested using and ReadLine loop for copying [OK]
Common Mistakes:
MISTAKES
Not closing streams properly
Using Write instead of WriteLine losing line breaks
Reading only one line instead of all
Master "File IO" in C Sharp (C#)
9 interactive learning modes - each teaches the same concept differently