Handling concurrent reading/writing of a file
<p>I have a web service that is generating random errors and I think I've found the fault.</p>

<p>Basically, it is reading a config file as follows, then loaded into an XmlDocument:</p>

<pre><code>var config = File.ReadAllText(filename);
xmlDoc.Load(config);
</code></pre>

<p>However, at a later time (maybe a second later) one of the config values is updated and the file saved</p>

<pre><code>xmlDoc.Save(filename);
</code></pre>

<p>So I'm now experiencing more errors (unfortunately the original developer added an empty try block so I can't check just now) during the first READ operation and I think it's because it's trying to read the file just as another process spawned from IIS is at the .Save part. I don't know how File.ReadAllText works and whether it will fail on a write locked file.</p>

<p>What's the best solution to handle this to ensure reading will always work? the value being written is just a counter and if it fails it is ignored as it's not that important but would prefer it was written. I guess I could put it into a separate config file and live with the error but I'd rather it was just one file.</p>

<p>Thanks.</p>