Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using statement FileStream and / or StreamReader - Visual Studio 2012 Warnings

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!

like image 374
JHubbard80 Avatar asked Aug 17 '12 05:08

JHubbard80


People also ask

Do you need to dispose FileStream?

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.

What is the use of FileStream?

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.

How does work in C#?

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.


1 Answers

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.

like image 106
Dan Avatar answered Sep 19 '22 04:09

Dan