我可以同时将多个 FileStream 对象制作成一个文件吗?

can i make Multiple FileStream objects to one file in the same time?

为什么在 fs2 对象中抛出错误??我已经在 fs 对象

中写了一个 FileShare.ReadWrite
     FileStream fs = new FileStream("hello.txt",FileMode.OpenOrCreate,FileAccess.ReadWrite,FileShare.ReadWrite);

        mama();

        Console.ReadKey();

    }
    static void mama()
    {
        FileStream fs2 = new FileStream("hello.txt", FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None);
        fs2.Read(new byte[3], 0, 3);
    }

谁能告诉我为什么会出现这个错误?

错误 = 进程无法访问文件 'C:\Users\iP\documents\visual studio 2015\Projects\ConsoleApplication32\ConsoleApplication32\bin\Debug\hello.txt' 因为它正被另一个进程使用。

因为您的代码从不关闭文件并且有一个打开的句柄

如果可以,请始终使用 using 语句,它将 flushclose 文件

using(var fs = new FileStream(...))
{
    // do stuff here
} // this is where the file gets flushed and closed

如果 2 个方法对同一个文件起作用,请在

中传递 FileStream
static void mama(FileStream fs )
{
    fs .Read(new byte[3], 0, 3);
}

您收到该错误是因为您将 FileShare.None 传递给第二个调用。如果将其更改为 FileShare.ReadWrite 以匹配第一个调用,则不会出现该问题。

这是因为 FileStream 构造函数在下面调用了 CreateFileW,如果您查看该函数的文档,它指出:

You cannot request a sharing mode that conflicts with the access mode that is specified in an existing request that has an open handle. CreateFile would fail and the GetLastError function would return ERROR_SHARING_VIOLATION.

您已经从使用 FileAccess.ReadWrite 作为访问模式的第一个请求中获得了一个打开的句柄,这与第二次调用中的 FileShare.None 冲突。