C# XMLDocument Save - 进程无法访问该文件,因为它正被另一个进程使用

标签 c# xmldocument xmlreader

我在调用加载后无法保存我的 XML 文件。此函数被调用两次 - 一次是在“toSave”设置为 false 时,第二次是在它被设置为 true 时。第二次,保存导致异常。我尝试向 XMLReader 添加 Dispose 和 Close 调用,但似乎无济于事。这是代码:

// Check if the file exists
if (File.Exists(filePath))
{
    try
    {
        // Load the file
        XmlReaderSettings readerSettings = new XmlReaderSettings();
        readerSettings.IgnoreComments = true;
        XmlReader reader = XmlReader.Create(filePath, readerSettings);

        XmlDocument file = new XmlDocument();
        file.Load(reader);

        XmlNodeType type;
        type = file.NodeType;
        if (toSave)
            ModifyXMLContents(file.FirstChild.NextSibling, null);
        else
            PopulateNode(file.FirstChild.NextSibling, null);

        // Save if we need to
        if (toSave)
            file.Save(filePath);

        reader.Dispose();
        reader.Close();
    }
    catch (Exception ex)
    {
        // exception is: "The process cannot access the file d:\tmp\10.51.15.2\Manifest.xml" because it is being used by another process
        Console.WriteLine(ex.Message);
    }
}

如有任何帮助,我们将不胜感激。

最佳答案

当您尝试保存时,您创建的 XmlReader 仍处于打开状态,因此它会锁定文件并阻止保存。

一旦加载到 XmlDocument 中,您就不再需要阅读器了,因此您可以在尝试保存之前关闭/处置它,然后保存应该会起作用。

例如:

XmlReaderSettings readerSettings = new XmlReaderSettings();
readerSettings.IgnoreComments = true;            

XmlDocument file = new XmlDocument();

using (XmlReader reader = XmlReader.Create(filePath, readerSettings))            
    file.Load(reader);

/* do work with xml document */

if (save)
    file.Save(filePath);

关于C# XMLDocument Save - 进程无法访问该文件,因为它正被另一个进程使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34772875/

相关文章:

c# - XmlReader - 自关闭元素不会触发 EndElement 事件?

c# - 使用 XmlReader 处理命名空间

c# - 哪个是paypal cancel url响应参数

c# - 设置整个组对目录的访问权限

java - 如何从 Java 中的 xml 文档对象中删除编码 ="UTF-8"独立 ="no"

c# - XmlElement 和 XmlNodeList 的隐式转换问题

c# - XmlReader 的行为与换行符不同

c# - 如何从已编译的引用库中判断调用程序集是否处于 DEBUG 模式

c# - MYSQL 连接到 C# 窗口应用程序

c# - 如何从XmlDocument中选择具有命名空间的节点?