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

我有一个简单的类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以只读方式运行,并且不需要锁定文件,这是达到预期结果的最佳方法,并解决这个问题?

谢谢

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

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

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

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

你可以这样做

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

代替

 xmlDoc.Load(xmlFilePath); 

如果文件不是太大而无法一次读入内存:

 xml.Load(new MemoryStream(File.ReadAllBytes(path))); 

尝试:

 xml.Load( new StreamReader( new FileStream( path, FileMode.Open, FileAccess.Read, FileShare.Read) ) );