Coding Practice: Handling Streams

Coding Practice: How do I prevent memory leaks when working with streams?
The safest practice is to leverage a “using” block whenever you work with streams.  The most dangerous practice is to create a stream as a static member of your class, since this creates a type of memory leak since streams are an unmanaged resource in .NET.

“Simply calling Dispose() on an object is not enough. The using keyword will prevent resource leaks even in the presence of an exception.”
– Daniel Turini

In practice, whenever you see a   stream, it should be surround in a “using” block as follows:

   using (StreamReader sr = new StreamReader(FileName))
      return sr.ReadToEnd();


About Chris VanHoose

Principal Software Architect at CT Lien Solutions
This entry was posted in Software Architecture and tagged , . Bookmark the permalink.

Leave a Reply

Please log in using one of these methods to post your comment: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.