如何同时打开一个文件不止一次

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

我正在尝试打开一个文件进行 Read/Write 访问,然后再次打开它,仅用于只读访问,但我一直收到错误消息,说第二次无法访问该文件,因为被另一个进程(第一个)使用。

// 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();

我理解参数 "FileShare.Read" 使我能够在不关闭第一个流的情况下再次打开文件进行读取...谁能告诉我我的错误在哪里?

将访问模式与共享模式进行比较。

文件 1 已打开 FileAccess.ReadWrite 并且 FileShare.Read-- 我相信它的功能如您所愿。

File2 已打开 FileAccess.Read 和 FileShare.Read。但是,File1 已将其打开 FileAccess.ReadWrite。打开只允许读取,因此失败。

您的第二次打开需要FileShare.Read写入才能正常工作。注意这里的缓存问题。