How to close this XML file after reading?

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?
 
P

Pavel Minaev

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.
 
J

Jon Skeet [C# MVP]

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);
}
....
 
J

Jon Skeet [C# MVP]

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.
 

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