C# Read/Write file from multiple applications
<p>I have scenario where we are maintaining Rates file(.xml) which is access by 3 different application running on 3 different servers. All 3 application uses RatesMaintenance.dll which has below 4 methods Load, Write, Read and Close. </p>

<p>All 3 applications writes into file continuously and hence I have added  Monitor.Enter and  Monitor.Exit mechanism assuming that these 3 operation from 3 different application will not collide. But at this moment, in some case, I am getting error - "<strong>Could not open the rates file</strong>"</p>

<p>As per my understanding, this means, some reason 3 application tries to access at same. <strong>Could anyone please suggest how to handle such scenario?</strong></p>

<pre><code>        Monitor.Enter(RatesFileLock);

        try
        {
            //Open Rates file
            LoadRatesFile(false);

            //Write Rates into file
            WriteRatesToFile();

            //Close Rates file
            CloseRatesFile();
        }
        finally
        {
            Monitor.Exit(RatesFileLock);
        }
</code></pre>

<p>Method signature of Load-</p>

<pre><code>LoadRatesFile(bool isReadOnly)
</code></pre>

<p>For opening file-</p>

<pre><code>new FileStream(RatesFilePath,
        isReadOnly ? FileMode.Open : FileMode.OpenOrCreate,
        isReadOnly ? FileAccess.Read : FileAccess.ReadWrite,
                isReadOnly ? FileShare.ReadWrite : FileShare.None);

.... remaining Rates reading logic code here
</code></pre>

<p>For reading Rates from file-</p>

<pre><code>Rates = LoadRatesFile(true);
</code></pre>

<p>For Writing Rates into file-</p>

<pre><code>if (_RatesFileStream != null &amp;&amp; _RatesInfo != null &amp;&amp; _RatesFileSerializer != null)
            {
                    _RatesFileStream.SetLength(0);

                    _RatesFileSerializer.Serialize(_RatesFileStream, _RatesInfo);
            }
</code></pre>

<p>In closing file method-</p>

<pre><code>            _RatesFileStream.Close();
            _RatesFileStream = null;
</code></pre>

<p>I hope, I try to explain my scenario in details. Please let me know in case anyone more details.</p>