How to close this XML file after reading?

  • Thread starter Thread starter K Viltersten
  • Start date Start date
K

K Viltersten

I'm using
XDocument document = XDocument.Load (XmlReader.Create (file));

to load in contents of a XML-file for parsing.
However, i noticed that the file seems to be
locked by the process and i can't save changes
made to it in VS until it ends.

How can i close the file?
 
You need to close the reader:

XDocument document;
using (var reader = XmlReader.Create(file))
{
document = XDocument.Load(reader);
}
Assuming that the entire file is parsed in the Load() method, you could
pass it a TextReader instance instead of the filename. Then you've got
access to the i/o object directly and can close it yourself.

He's not passing the filename as it is - he's passing XmlReader already.
It does seem like the XDocument class itself ought to have a Dispose() or
Close(), or maybe just close the source file immediately after parsing. I
might be missing something here. :)

XDocument.Load(string) does close the file after loading it.
XDocument.Load(XmlReader), which is used in this case, obviously doesn't.
 
Peter Duniho said:
Assuming that the entire file is parsed in the Load() method, you could
pass it a TextReader instance instead of the filename. Then you've got
access to the i/o object directly and can close it yourself.

It does seem like the XDocument class itself ought to have a Dispose() or
Close(), or maybe just close the source file immediately after parsing. I
might be missing something here. :)

I think it's the XmlReader which needs to be disposed:

XDocument document;
using (XmlReader reader = XmlReader.Create(file))
{
document = XDocument.Load(reader);
}
....
 
Peter Duniho said:
[...]
It does seem like the XDocument class itself ought to have a Dispose()
or
Close(), or maybe just close the source file immediately after
parsing. I
might be missing something here. :)

I think it's the XmlReader which needs to be disposed:

Well, yes...or the TextReader. My second paragraph was more about what
the class should have in it, as opposed to what it actually does have in
it. :)

But I don't think it should really be up to the XDocument to dispose of
anything in this case. It's not allocating the resources, nor wrapping
them in a permanent way, so I think it's entirely reasonable for the
caller to still "own" them and have to dispose of them.
 
Back
Top