Search code examples
c#.netwindowsfile-iofilestream

Cannot open filestream for reading but still I am able to copy the file?


This line:

using (FileStream fs = File.Open(src, FileMode.Open, FileAccess.Read, FileShare.Read))

throws:

System.IO.IOException: The process cannot access the file 'X' because it is being used by another process.

When I replace the line with:

File.Copy(src, dst, true);
using (FileStream fs = File.Open(dst, FileMode.Open, FileAccess.Read, FileShare.Read))

it works.

But why I can copy, which surely reads the whole content of file, while being restricted from directly reading the file? Is there a workaround?


Solution

  • When you open a file there is a check for access modes and sharing modes. The access modes of any process must be compatible with the sharing modes of others. So if A wants access to read, others must have allowed reading in sharing mode. Same for writing.

    If process A has opened a file for writing and you say SharingMode.Read the call will fail. You are in this case saying "others may only read from the file, not write."

    If you specify ShareMode.ReadWrite you're saying "others can read or write, I don't care" and if no other process has specified ShareMode.Write you are allowed to read from the file.