You want to copy the contents of one text file to another using StreamReader and StreamWriter. Which code snippet correctly performs this task?
hard🚀 Application Q15 of 15
C Sharp (C#) - File IO
You want to copy the contents of one text file to another using StreamReader and StreamWriter. Which code snippet correctly performs this task?
Ausing (var reader = new StreamReader("source.txt")) {
string content = reader.ReadToEnd();
var writer = new StreamWriter("dest.txt");
writer.Write(content);
}
Busing (var writer = new StreamWriter("dest.txt")) {
using (var reader = new StreamReader("source.txt")) {
string line;
while ((line = reader.ReadLine()) != null) {
writer.WriteLine(line);
}
}
}
Cvar reader = new StreamReader("source.txt");
var writer = new StreamWriter("dest.txt");
string line = reader.ReadLine();
while (line != null) {
writer.WriteLine(line);
line = reader.ReadLine();
}
reader.Close();
writer.Close();
Dusing (var reader = new StreamReader("source.txt")) {
using (var writer = new StreamWriter("dest.txt")) {
string line;
while ((line = reader.ReadLine()) != null) {
writer.WriteLine(line);
}
}
}
Step-by-Step Solution
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 nested using blocks 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 D
Quick Check:
Nested using + line loop = A [OK]
Quick Trick:Use nested 'using' blocks and loop ReadLine [OK]
Common Mistakes:
MISTAKES
Not disposing writer properly
Reversing reader and writer order in using blocks
Not looping to read all lines
Not disposing writer in option D
Master "File IO" in C Sharp (C#)
9 interactive learning modes - each teaches the same concept differently