Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disposing an XDocument object

How do I "dispose" an XDocument object? I am using it to parse an XML string and then save the file to the file system. In the same method I then need to access this file and run a command line tool on it.

The code is as follows:

string filepath = "...";
string filename = "...";
XDocument xdoc = XDocument.Parse(xmlString);
xdoc.Save(filepath + filename);

Process p = Process.Start(new ProcessStartInfo("rst.exe", args)); // the args use the file saved above

I put a breakpoint on the line where I call the command line tool, and then tried to open the file manually myself, but it wouldn't load until I stopped the debugger.

edit: Thanks for the answers. I've narrowed down the problem.. after the file is saved, and with the breakpoint on "Process p = ...", I am able to open the file, but I can't access it using http://qualifiedapppath/path/file.xml, and the command line tool I am using will only accept a URL as a parameter. After stopping the debugger, I am able to access the file through http. What process is preventing access to it while the method is running?

like image 342
notAnonymousAnymore Avatar asked Oct 13 '12 16:10

notAnonymousAnymore


2 Answers

XDocument is a class that stores an in-memory copy of an XML document. Classes implement IDisposable because they use unmanaged resources other than memory. Memory is already capably managed by the garbage collector.

Since XDocument only consumes memory, it doesn't have a need for a Dispose method.

like image 184
Hans Passant Avatar answered Oct 11 '22 02:10

Hans Passant


No, you don't - it doesn't even implement IDisposable. The XDocument and XElement classes use XmlReader under the covers and handle the disposing of the underlying reader for you. Simply right-click on XDocument class and select Go To Definition, you may not find IDisposable implemented by this class.

To reclaim the memory, set XDocument object reference to null and GC will recollect the acquired memory.

ADDED:

For the second part of your question, use this Uri if file is available locally this way:

var uri = new Uri("file:///C:/path/file.xml");

You can also verify the file location using this piece of code:

if (uri.IsFile)
{
    var filePath = uri.LocalPath; // C:/path/file.xml
}

You can use HTTP if you configure the virtual directory in IIS to locate that file.

like image 39
Furqan Safdar Avatar answered Oct 11 '22 02:10

Furqan Safdar