Need to close FileStream

  • Thread starter Thread starter tshad
  • Start date Start date
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
 
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
 
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
 
Back
Top