Bird
Raised Fist0

Which of the following is the correct syntax to write text to a file using StreamWriter in C#?

easy📝 Syntax Q3 of Q15
C Sharp (C#) - File IO
Which of the following is the correct syntax to write text to a file using StreamWriter in C#?
AStreamWriter.WriteLine("file.txt", "Hello");
BStreamWriter sw = new StreamWriter.WriteLine("file.txt", "Hello");
CStreamWriter sw = new StreamWriter("file.txt"); sw.Write("Hello"); sw.Close();
Dusing(StreamWriter sw = new StreamWriter("file.txt")) { sw.WriteLine("Hello"); }
Step-by-Step Solution
Solution:
  1. Step 1: Recognize correct StreamWriter usage

    Using statement ensures proper disposal of StreamWriter after writing.
  2. Step 2: Validate syntax correctness

    using(StreamWriter sw = new StreamWriter("file.txt")) { sw.WriteLine("Hello"); } correctly creates StreamWriter and writes a line inside using block.
  3. Final Answer:

    using(StreamWriter sw = new StreamWriter("file.txt")) { sw.WriteLine("Hello"); } -> Option D
  4. Quick Check:

    StreamWriter write syntax = using block with WriteLine [OK]
Quick Trick: Use 'using' to auto-close StreamWriter after writing [OK]
Common Mistakes:
MISTAKES
  • Calling WriteLine as a static method
  • Missing using block or Close call
  • Incorrect constructor or method chaining

Want More Practice?

15+ quiz questions · All difficulty levels · Free

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