C#与XML.load()锁定在磁盘上导致错误的文件 [英] c# xml.Load() locking file on disk causing errors

查看:336
本文介绍了C#与XML.load()锁定在磁盘上导致错误的文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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:\CvarUAT\ReportWriterSettings.xml'' **because it is being used by another process**


当这个类是通过并行运行这两个尝试加载XML文件上面的组件两个正在运行的实例使用

发生这种情况,这是合法行为和应用程序所需。

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.

我只希望在XML从磁盘读取一次,并释放到磁盘上的文件的任何引用,并从该点向前记忆表征使用。

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?

感谢

推荐答案

这要看你从文件中需要什么,

it depends on what you need from the file,

如果你需要它是threasdsafe你需要impliment一个互斥锁实例之间的负载,

If you need it to be threasdsafe you would need to impliment a mutex to lock the loading between instance,

如果你不真正需要的是线程安全的加载(即该文件不会改变),你可以通过一个文件流加载它,然后从流

If you dont really need thread safe loading (i.e. the file never changes) you could load it via a filestream then load the XmlDocument from the stream

            FileStream xmlFile = new FileStream(xmlFilePath, FileMode.Open,
FileAccess.Read, FileShare.Read);
            xmlDoc.Load(xmlFile);

这篇关于C#与XML.load()锁定在磁盘上导致错误的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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