繁体   English   中英

如何同时打开多个文件

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

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

// 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”使我能够在不关闭第一个 stream 的情况下再次打开文件进行读取...有人可以告诉我我的错误在哪里吗?

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

File1 是打开的 FileAccess.ReadWrite 和 FileShare.Read——它的功能正如我相信你想要的那样。

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

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

您有一些可能不相关的错误,即未正确处理文件连接。 但这不是唯一的错误。 异常处理是我的一个小烦恼,而这个很糟糕。 通常链接这两篇文章以使人们快速了解:

关于问题:

您打开文件两次的整个想法XY 问题的气味。 您应该适当地返回 go。 分开存储读写和读取工作的指针应该很容易。 或者只是不需要两个代码来处理它。

至于问题。 这些股票期权中的每一个最后都有这个小句子:

但是,即使指定了此标志,仍可能需要其他权限才能访问该文件。

所以可能是操作系统或文件系统不允许多个文件连接。

但是,即使操作系统阻止它,也有一种方法 - Memory Mapped Files 虽然主要是一种进程间通信方法,但我可能在同一个进程中有两个连接(我需要检查,因为它可能有一个 Singelton 模式)。 这也意味着您必须使用非托管指针。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM