Bird
0
0

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:
  1. 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.
  2. Step 2: Verify reading and writing logic

    It reads line by line until null, writing each line to the destination file correctly.
  3. Final Answer:

    Correct nested using blocks with line-by-line copy -> Option D
  4. 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

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More C Sharp (C#) Quizzes