我有一个简单的类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
}
问题是我在加载时遇到以下错误:
System.IO.IOException: The process cannot access the file ''C:\CvarUAT\ReportWriterSettings.xml'' **because it is being used by another process**
当这个类被并行运行的组件的两个运行实例用于尝试加载上面的xml文件时,会发生这种情况,这是合法行为并且是应用程序所需的。
我只想读取磁盘上的xml一次并释放对磁盘上文件的任何引用,并使用从那一点开始的内存表示。
我会假设Load以只读方式运行,并且不需要锁定文件,这是达到预期结果的最佳方法,并解决这个问题?
由于
答案 0 :(得分:37)
你可以这样做
using (Stream s = File.OpenRead(xmlFilePath))
{
xmlDoc.Load(s);
}
而不是
xmlDoc.Load(xmlFilePath);
答案 1 :(得分:21)
这取决于您对文件的需求,
如果你需要它是threasdsafe,你需要使用互斥锁来锁定实例之间的加载,
如果您真的不需要线程安全加载(即文件永远不会更改),您可以通过文件流加载它然后从流中加载XmlDocument
FileStream xmlFile = new FileStream(xmlFilePath, FileMode.Open,
FileAccess.Read, FileShare.Read);
xmlDoc.Load(xmlFile);
答案 2 :(得分:0)
如果文件不是太大而无法一次读入内存:
xml.Load(new MemoryStream(File.ReadAllBytes(path)));
答案 3 :(得分:-2)
尝试:
xml.Load(
new StreamReader(
new FileStream(
path,
FileMode.Open,
FileAccess.Read,
FileShare.Read)
)
);