Salo7ty
Salo7ty

Reputation: 495

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

why in fs2 object throw error ?? i already have written a FileShare.ReadWrite in fs object

     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);
    }

can any one tell me why this error ?

error = The process cannot access the file 'C:\Users\iP\documents\visual studio 2015\Projects\ConsoleApplication32\ConsoleApplication32\bin\Debug\hello.txt' because it is being used by another process.

Upvotes: 0

Views: 485

Answers (2)

Herohtar
Herohtar

Reputation: 5613

You're getting that error because you're passing FileShare.None to the second call. If you change that to FileShare.ReadWrite to match the first call, you won't have that problem.

The reason for this is because the FileStream constructor calls CreateFileW underneath, and if you take a look at the documentation for that function, it states:

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.

You already have an open handle from the first request using FileAccess.ReadWrite as the access mode, which conflicts with FileShare.None in the second call.

Upvotes: 1

TheGeneral
TheGeneral

Reputation: 81493

Because your code never closes the file and has an open handle to it

If you can, always use the using statement, it will flush and close the file

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

If 2 methods are working on the same file, pass the FileStream in

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

Upvotes: 0

Related Questions