The new Visual Studio 2012 is complaining about a common code combination I have always used. I know it seems like overkill but I have done the following in my code 'just to be sure'.
using (var fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) { using (var sr = new StreamReader(fs)) { // Code here } }
Visual studio is 'warning' me that I am disposing of fs more than once. So my question is this, would the proper way to write this be:
using (var fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) { var sr = new StreamReader(fs); // do stuff here }
Or should I do it this way (or some other variant not mentioned).
var fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); using (var sr = new StreamReader(fs)) { // Code here }
I searched several questions in StackOverflow but did not find something that addressed the best practice for this combination directly.
Thank you!
In the specific case of a FileStream , you don't need to dispose it to close the file, you only need to use the Close method. You should however dispose of the FileStream object anyway, as it has a finalizer.
Remarks. Use the FileStream class to read from, write to, open, and close files on a file system, and to manipulate other file-related operating system handles, including pipes, standard input, and standard output.
The using declaration calls the Dispose method on the object in the correct way when it goes out of scope. The using statement causes the object itself to go out of scope as soon as Dispose is called. Within the using block, the object is read-only and can't be modified or reassigned.
The following is how Microsoft recommends doing it. It is long and bulky, but safe:
FileStream fs = null; try { fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); using (TextReader tr= new StreamReader(fs)) { fs = null; // Code here } } finally { if (fs != null) fs.Dispose(); }
This method will always ensure that everything is disposed that should be despite what exceptions may be thrown. For example, if the StreamReader
constructor throws an exception, the FileStream
would still be properly disposed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With