Use different pattern with stream, without explicit closing (I know, the documentation is a bit confusing):
using (FileStream stream = new FileStream( )) {
}
Besides, regardless of the closing problems, it's important to guarantee that you eventually call
System.IDisposable.Dispose()
for each and every object implementing this interface. That's why it's good to use the
using
statement (not to be confused with
using
directive!):
https://msdn.microsoft.com/en-us/library/yh598w02.aspx[
^].
One more suggestion: most likely, you don't need to use
FileStream
directly. It is really needed only if you have read/write stream, which is a rare case; usually, your stream is read-only or write-only. Therefore, it's usually much better to use one or more of these classes:
https://msdn.microsoft.com/en-us/library/system.io.streamwriter%28v=vs.110%29.aspx[
^],
https://msdn.microsoft.com/en-us/library/system.io.streamreader%28v=vs.110%29.aspx[
^],
https://msdn.microsoft.com/en-us/library/system.io.binarywriter%28v=vs.110%29.aspx[
^],
https://msdn.microsoft.com/en-us/library/system.io.binaryreader%28v=vs.110%29.aspx[
^].
—SA