如何多次打开文件

我试图打开文件进行读/写访问,然后再次打开它,仅用于读访问,但是我不断收到一个错误消息,说第二次无法访问该文件,因为该文件已被另一个文件使用流程(第一个)。

// 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,Fileaccess.Read,FileShare.Read);
    MessageBox.Show("File2 is Open for Read",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”使我可以再次打开文件以进行读取,而无需关闭第一个流……有人可以告诉我我的错误在哪里吗?

qwweerrttyyuuiioop 回答:如何多次打开文件

比较访问模式和共享模式。

File1是打开的FileAccess.ReadWrite和FileShare.Read,它按我的预期运行。

File2打开FileAccess.Read和FileShare.Read。但是,File1可以打开FileAccess.ReadWrite。打开仅允许读取,因此失败。

您的第二次打开需要FileShare.ReadWrite才能正常工作。提防缓存问题。

本文链接:https://www.f2er.com/3130986.html

大家都在问