At first glance, this looks like false positive, because disposing of BinaryReader will also remove the FileStream returned by File.OpenRead :
From: http://msdn.microsoft.com/en-us/library/azy2k2bx.aspx
When the rights deletion option is true, this method releases all resources owned by any managed objects that reference this BinaryReader. This method calls the Dispose method for each reference object.
However, there is one corner case where FileStream is not really used: when the BinaryReader constructor throws an exception!
Decision:
The correct way to write code would be as follows:
using (var fs = File.OpenRead(path)) { BinaryReader br = new BinaryReader(fs); myByte = br.ReadByte(); }
Background:
BinaryReader contains only a link to FileStream and therefore does not need to be deleted.
Code analysis shares this view.
BTW: When using this solution for a recording stream, it is important to clear the recording before the stream is deleted:
using (var fileStream = new FileStream(...)) { var writer = new StreamWriter(fileStream); writer.WriteLine(...); writer.Flush();
If you forget about it, your stream may not contain everything that was written using StreamWriter .
source share