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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With