471,347 Members | 1,834 Online
Bytes | Software Development & Data Engineering Community
Post +

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 471,347 software developers and data experts.

Need to close FileStream

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
Jul 30 '08 #1
4 2177
On Jul 30, 12:59*pm, "tshad" <ts...@dslextreme.comwrote:
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
Jul 30 '08 #2
According to the documentation:

http://msdn.microsoft.com/en-us/libr...r_members.aspx

" Close - Closes the StreamReader object and the underlying stream, and
releases any system resources associated with the reader. (Overrides
TextReader.Close().) "

Andrew Faust

"tshad" <ts***@dslextreme.comwrote in message
news:#p**************@TK2MSFTNGP02.phx.gbl...
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
Jul 30 '08 #3
Much to my annoyance sr.Close will also close the stream.
Pete
Jul 30 '08 #4
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

"Peter Morris" <mr*********@SPAMgmail.comwrote in message
news:eZ****************@TK2MSFTNGP02.phx.gbl...
Much to my annoyance sr.Close will also close the stream.
Pete

Aug 25 '08 #5

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

reply views Thread by Terry Olsen | last post: by
46 posts views Thread by Bruce W. Darby | last post: by
18 posts views Thread by Eric B. | last post: by
reply views Thread by Ronak mishra | last post: by

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.