【问题标题】:C# XMLDocument Save - Process cannot access the file because it is being used by another processC# XMLDocument 保存 - 进程无法访问该文件,因为它正被另一个进程使用
【发布时间】:2016-04-18 19:01:10
【问题描述】:

调用 load.xml 后,我无法保存我的 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);
    }
}

任何帮助将不胜感激。

【问题讨论】:

  • 请勿发布代码图片。复制并粘贴到问题中 - 并非所有用户都可以访问图像,或者他们可能在移动设备上并且无法清楚地看到图像。
  • 我建议看看这篇文章,了解如何有效地创建 XML 文档 Other XML Technologies
  • 您尝试在关闭阅读器之前保存文件。很可能是读者锁定了文件。在调用Save 之前尝试关闭阅读器(并考虑使用using 块)。
  • 对不起那个蒂姆。我通常发布代码,但认为这样更容易。干杯

标签: c# xmldocument xmlreader


【解决方案1】:

您创建的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);

【讨论】:

    【解决方案2】:

    对我来说,这是由于文件被写入包含许多 (100k) 其他文件的目录。一旦我清除了所有其他文件,问题就消失了。 NTFS 似乎在单个文件夹中包含大量文件时变得暴躁。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-01-17
      • 2013-06-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-10
      相关资源
      最近更新 更多