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

前端 未结 4 1764
醉梦人生
醉梦人生 2020-12-05 23:46

I have a simple class XmlFileHelper as follows:

public class XmlFileHelper
{
    #region Private Members

    private XmlDocument xmlDoc = new XmlDocument();         


        
相关标签:
4条回答
  • 2020-12-06 00:25

    it depends on what you need from the file,

    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);
    
    0 讨论(0)
  • 2020-12-06 00:28

    try:

    xml.Load(
           new StreamReader(
               new FileStream(
                      path, 
                      FileMode.Open, 
                      FileAccess.Read, 
                      FileShare.Read)
                )
              );
    
    0 讨论(0)
  • 2020-12-06 00:32

    You can do this

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

    instead of

    xmlDoc.Load(xmlFilePath);
    
    0 讨论(0)
  • 2020-12-06 00:40

    If the file isn't too big to read into memory all at once:

    xml.Load(new MemoryStream(File.ReadAllBytes(path)));
    
    0 讨论(0)
提交回复
热议问题