处置XDocument对象 [英] Disposing an XDocument object

查看:75
本文介绍了处置XDocument对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何处置" XDocument对象?我使用它来解析XML字符串,然后将文件保存到文件系统.然后,使用相同的方法,我需要访问该文件并在其上运行命令行工具.

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.

代码如下:

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.

编辑:感谢您的回答.我已经缩小了问题的范围..保存文件后,在"Process p = ..."上设置了断点,我 am 可以打开文件,但无法访问它使用http://qualifiedapppath/path/file.xml,而我正在使用的命令行工具将仅接受URL作为参数.停止调试器后,我可以通过http访问文件.在该方法运行时,什么进程阻止对其进行访问?

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?

推荐答案

不,您没有-它甚至没有实现IDisposable. XDocument和XElement类在幕后使用XmlReader并为您处理基础阅读器的处理.只需右键单击XDocument类并选择转到定义,您可能找不到该类实现的IDisposable.

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.

要回收内存,请将XDocument对象引用设置为null,GC将重新收集获取的内存.

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

添加:

对于问题的第二部分,如果文件在本地可用,请使用此Uri:

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
}

如果在IIS中配置虚拟目录以找到该文件,则可以使用HTTP.

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

这篇关于处置XDocument对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆