I was building a simple web system which relied on XML files. On initiation, the system would open the XML config file, read it and include other XML files defined in it:
1 2 3 4 |
FileStream fr = new FileStream(xmlPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); //Creating the document XmlDocument myXmlDocument = new XmlDocument(); myXmlDocument.Load(fr); |
The operation was done within a WebForm and it worked just fine.
I also had a WCF service whose job was to the update XML file. However, it was resolutely throwing me the error:
The process cannot access the file '' because it is being used by another process
The message is clear enough: the resource I want to access is currently being used by another process. The error only occurred on the first service call which indicated there was something wrong with the initialization. Indeed, I didn't close the stream:
1 2 3 4 5 6 |
XmlTextReader xml = new System.Xml.XmlTextReader(file + ".xml"); DataSet ds2 = new DataSet(); ds2.ReadXml(xml); ds.Merge(ds2); //CLOSE THE BLOODY STREAM!! xml.Close(); |
Heh, there are lessons to be learnt from this. Firstly, always remember to close opened files. Secondly, although the message says 'process', if you have multiple threads attempting to access the same file, the same error will be thrown.