Need to close FileStream

T

tshad

If I have the following:

fs = new FileStream(xmlFile, FileMode.Open,
System.IO.FileAccess.Read);
sr = new StreamReader(fs);

will sr.Close() also close the fs? Or do I need to close both?

Thanks,

Tom
 
I

Ignacio Machin ( .NET/ C# MVP )

If I have the following:

            fs = new FileStream(xmlFile, FileMode.Open,
System.IO.FileAccess.Read);
            sr = new StreamReader(fs);

will sr.Close() also close the fs?  Or do I need to close both?

Thanks,

Tom

Hi,

Why not using a StreamReader from the start (if it's a Xml use
XmlReader instead)

if for some reason you still need to use your code do it like this:
using( FileStream fs = new FileStream(xmlFile, FileMode.Open,
System.IO.FileAccess.Read) ){
using( StreamReader sr = new StreamReader(fs) ){
}

}


It makes sure that the objects are disposed correctly
 
T

tshad

So if I am going to read multiple files,

After the first file, I would do an sr.Close() (which closes fs as well).
So then I would do another:

fs = new FileStream(Anotherfile, FileMode.Open,
System.IO.FileAccess.Read);

And another:

sr = new StreamReader(fs);

but I never need to do an fs.Close() then.

Thanks,

Tom
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top