Search code examples
c#filestream

How to open a file more than once at the same time


I am trying to open a file for Read/Write access and then open it again, only for Read access only, but I keep getting an error saying that the second time is not possible to access the file because is used by another process (the first one).

// Open a file for read/write and then only for read without closing the firts stream

string FileName = "C:\\MisObras\\CANCHA.REC"; // Replace this with any existing folder\file 
FileStream File1 = null,
        File2 = null;
try
{
    File1 = new FileStream(FileName, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.Read);
    MessageBox.Show("File1 is Open for Read/Write", "", MessageBoxButtons.OK, MessageBoxIcon.Information);

    File2 = new FileStream(FileName, FileMode.OpenOrCreate, FileAccess.Read, FileShare.Read);
    MessageBox.Show("File2 is Open for Read", "", MessageBoxButtons.OK, MessageBoxIcon.Information);
} catch (Exception e)
{
    System.Windows.Forms.MessageBox.Show (e.Message,"Error de Archivo", System.Windows.Forms.MessageBoxButtons.OK,System.Windows.Forms.MessageBoxIcon.Error);
}

if (File1 != null) File1.Close();
if (File2 != null) File2.Close();

I understand the parameter "FileShare.Read" enables me to open again the file for reading without closing the first stream... Can some one tell me where is my mistake?


Solution

  • Compare the access modes with the sharing modes.

    File1 is open FileAccess.ReadWrite and FileShare.Read--it functions as I believe you intend.

    File2 is open FileAccess.Read and FileShare.Read. However, File1 has it open FileAccess.ReadWrite. The open only allows Read, thus it fails.

    Your second open needs FileShare.ReadWrite in order to work correctly. Beware of caching issues here.