Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
137 views
in Technique[技术] by (71.8m points)

c# xml.Load() locking file on disk causing errors

I have a simple class XmlFileHelper as follows:

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
}

The issue is I am getting the following error on Load:

System.IO.IOException: The process cannot access the file ''C:CvarUATReportWriterSettings.xml'' **because it is being used by another process**

this occurs when this class is used to by two running instances of a component running in parallel both attempting to load the xml file above, this is legitimate behaviour and required by the application.

I only want to read in the xml off disk once and release any reference to the file on disk and use an in memory representation from that point forward.

I would have assumed Load operates in a readonly fashion and would have no need to lock the file, what is my best way to achieve the desired result and get around this issue?

Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can do this

using (Stream s = File.OpenRead(xmlFilePath))
{
    xmlDoc.Load(s);
}

instead of

xmlDoc.Load(xmlFilePath);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...