Closing a stream(easy question)

  • Thread starter Thread starter Nick
  • Start date Start date
N

Nick

Hi,
simple question

XmlDocument doc = new XmlDocument();
FileStream file = new FileStream
(PathAndFileName,FileMode.Open,FileAccess.Read,FileShare.ReadWrite);
doc.Load(file);

should I now call file.close or do I not need to??

Thanks
Nick
 
should I now call file.close or do I not need to??

yes you should call file.Close(). the whole stream is read in the Load()
method and it's not necessary to leave the file opened.

Chris
 
Enclose the doc.Load(...) statement in the try-finally block and add the
following in the "finally" clause:

try
{
file.Close();
}
catch(IOException)
{
// Optionally add something like this here:
// Debug.WriteLine("Failed to close the file");
}
 
Hi Nick,

Yes, you should call file.Close(); XmlDocument.Load will not close the stream itself. In any case, calling file.Close() on an already closed file will just be ignored and will do no harm.

Happy coding!
Morten Wennevik [C# MVP]
 
Yes, you should call file.Close(); XmlDocument.Load will not close the
stream itself. In any case, calling file.Close() on an already closed file will
just be ignored and will do no harm.

after calling close on a FileStream, it will likely become null. the
Close() method of FileStream calls Dispose(). I haven't tested it, but I'm
fairly sure it will be null in all cases.

Chris
 
Calling Close() will release any resources tied to it, in this case the file. The FileStream object will remain intact however, so you can safely call Close() as many times as you want.

Happy coding!
Morten Wennevik [C# MVP]
 
Chris said:
after calling close on a FileStream, it will likely become null.

No it won't. Objects don't just disappear because you call Close on
them. If you still have a reference to an object, that reference isn't
going to become null on its own.
the Close() method of FileStream calls Dispose(). I haven't tested it, but I'm
fairly sure it will be null in all cases.

Could you clarify exactly what you think "will be null"?
 
Back
Top