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

时间:2023-11-25 21:01:44

本文转自:http://*.com/questions/1812598/c-sharp-xml-load-locking-file-on-disk-causing-errors

问:

I have a simple class XmlFileHelper as follows:

publicXmlFileHelper(string xmlFilePath)
    {
        this.xmlFilePath = xmlFilePath;
        xmlDoc.Load(xmlFilePath);
    }

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.

答1:

You can do this

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

instead of

xmlDoc.Load(xmlFilePath);

答2:

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