Bird
0
0

How can you safely read a file and ensure it is closed automatically even if an error occurs?

hard🚀 Application Q9 of 15
C Sharp (C#) - File IO
How can you safely read a file and ensure it is closed automatically even if an error occurs?
ACall StreamReader.Close() manually after reading
BUse a using statement with StreamReader
CUse File.ReadAllText without any try-catch
DOpen file with FileStream and never close it
Step-by-Step Solution
Solution:
  1. Step 1: Understand resource management

    Using statement ensures automatic disposal of StreamReader even on exceptions.
  2. Step 2: Compare other options

    Manual Close may be skipped on errors; ReadAllText reads but no error handling; never closing file causes resource leaks.
  3. Final Answer:

    Use a using statement with StreamReader -> Option B
  4. Quick Check:

    Using statement ensures safe file closing [OK]
Quick Trick: Wrap StreamReader in using to auto-close file [OK]
Common Mistakes:
MISTAKES
  • Forgetting to close files
  • Relying on manual Close
  • Ignoring exceptions

Want More Practice?

15+ quiz questions · All difficulty levels · Free

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