Back to results for “I/O Streams”
C# › File I/O & Streams

How does the 'using' statement (or 'using' declaration) ensure a FileStream is properly closed, even if an exception occurs?

Intermediate

Answer

'using' automatically calls Dispose() on the resource when execution leaves its scope — whether normally or via an exception — guaranteeing the underlying file handle is released; this is essential for FileStream and other IDisposable resources like database connections, since forgetting to dispose them can leave files locked or exhaust OS handles.
using (FileStream stream = File.OpenRead("data.txt")) {
  // stream is guaranteed to be disposed when this block exits, even on exception
}

// Modern C# 8+ 'using declaration' (disposed at end of enclosing scope)
using FileStream stream2 = File.OpenRead("data.txt");
Real-world example Guaranteeing a file lock is released immediately after processing, even if the processing code throws an exception midway.

Common follow-ups: What interface must a type implement to be usable with a 'using' statement?