c#xml.Load()锁定磁盘上的文件导致错误

m3n*_*tat 22 c# xml load locking

我有一个简单的类XmlFileHelper如下:

public class XmlFileHelper
{
    #region Private Members

    private XmlDocument xmlDoc = new XmlDocument();
    private string xmlFilePath;

    #endregion

    #region Constructor

    public XmlFileHelper(string xmlFilePath)
    {
        this.xmlFilePath = xmlFilePath;
        xmlDoc.Load(xmlFilePath);
    }

    #endregion

    #region Public Methods

    public XmlNode SelectSingleNode(string xPathQuery)
    {
        return xmlDoc.SelectSingleNode(xPathQuery);
    }

    public string GetAttributeValueByName(XmlNode node, string attributeName)
    {
        return node.Attributes.GetNamedItem(attributeName).Value;
    }

    #endregion

    #region Public Properties

    public string XmlFilePath
    {
        get
        {
            return xmlFilePath;
        }
    }

    #endregion
}
Run Code Online (Sandbox Code Playgroud)

问题是我在加载时收到以下错误:

System.IO.IOException: The process cannot access the file ''C:\CvarUAT\ReportWriterSettings.xml'' **because it is being used by another process**
Run Code Online (Sandbox Code Playgroud)

当这个类被并行运行的组件的两个运行实例用于尝试加载上面的xml文件时,会发生这种情况,这是合法的行为并且是应用程序所需要的.

我只想读取磁盘上的xml一次,并释放对磁盘上文件的任何引用,并使用从那一点开始的内存表示.

我会假设Load以只读方式运行,并且不需要锁定文件,达到预期结果的最佳方法是什么?解决这个问题?

谢谢

Joã*_*elo 37

你可以这样做

using (Stream s = File.OpenRead(xmlFilePath))
{
    xmlDoc.Load(s);
}
Run Code Online (Sandbox Code Playgroud)

代替

xmlDoc.Load(xmlFilePath);
Run Code Online (Sandbox Code Playgroud)


Pha*_*bus 22

这取决于你需要从文件中,

如果你需要它是threasdsafe,你需要使用互斥锁来锁定实例之间的加载,

如果您真的不需要线程安全加载(即文件永远不会更改),您可以通过文件流加载它然后从流加载XmlDocument

            FileStream xmlFile = new FileStream(xmlFilePath, FileMode.Open,
FileAccess.Read, FileShare.Read);
            xmlDoc.Load(xmlFile);
Run Code Online (Sandbox Code Playgroud)