How to remove File.OpenRead ()

How do I handle File.OpenRead () correctly. Am I currently using the code below?

using (BinaryReader br = new BinaryReader(File.OpenRead(path))) { myByte = br.ReadByte(); } 

I get the following in Visual Studio when analyzing the code:

Warning 1 CA2000: Microsoft.Reliability: in the method 'Program.Main (line [])', the object 'File.OpenRead (path)' is not deleted along all the exception paths. Calling System.IDisposable.Dispose on object 'File.OpenRead (path)' before all references to it is beyond the scope.

+4
source share
4 answers

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(); // <-- Important } 

If you forget about it, your stream may not contain everything that was written using StreamWriter .

+15
source

Description:

 using (Filestream fs = File.OpenRead(Path)) { using (BinaryReader br = new BinaryReader(fs)) { myByte = br.ReadByte(); } } 
+2
source

File.OpenRead returns a FileStream, which is also unavailable. You can put it in an external use block if you want, or declare it and delete it outside of your current use.

0
source

Both FileStream created by File.OpenRead and BinaryReader that you create in this FileStream must be deleted, so you need an explicit link to each:

 using(FileStream fs = File.OpenRead(path)) using(BinaryReader br = new BinaryReader(fs)) { myByte = br.ReadByte(); } 
0
source

Source: https://habr.com/ru/post/1345579/


All Articles