Bird
Raised Fist0

You want to write multiple lines to a file and ensure the file is closed properly even if an exception occurs. Which code snippet correctly uses the using statement for this?

hard🚀 Application Q8 of Q15
C Sharp (C#) - File IO
You want to write multiple lines to a file and ensure the file is closed properly even if an exception occurs. Which code snippet correctly uses the using statement for this?
Ausing (var writer = new StreamWriter("file.txt")) { writer.WriteLine("Line1"); writer.WriteLine("Line2"); }
Bvar writer = new StreamWriter("file.txt"); writer.WriteLine("Line1"); writer.WriteLine("Line2"); writer.Close();
CStreamWriter writer; using writer = new StreamWriter("file.txt"); writer.WriteLine("Line1");
Dusing StreamWriter writer = StreamWriter("file.txt"); writer.WriteLine("Line1");
Step-by-Step Solution
Solution:
  1. Step 1: Check proper using statement syntax

    using (var writer = new StreamWriter("file.txt")) { writer.WriteLine("Line1"); writer.WriteLine("Line2"); } uses using with braces and new StreamWriter correctly.
  2. Step 2: Verify resource safety

    Using ensures writer is disposed even if exceptions occur during writing.
  3. Final Answer:

    using (var writer = new StreamWriter("file.txt")) { writer.WriteLine("Line1"); writer.WriteLine("Line2"); } -> Option A
  4. Quick Check:

    Using with braces ensures safe file writing [OK]
Quick Trick: Use using with braces for multiple writes safely [OK]
Common Mistakes:
MISTAKES
  • Not using using causes resource leaks on exceptions
  • Incorrect using syntax without new keyword
  • Trying to declare using without var or type

Want More Practice?

15+ quiz questions · All difficulty levels · Free

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