无法打开文件流进行读取,但我仍然可以复制文件?

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

这一行:

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

投掷:

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

当我将行替换为:

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

有效。

但是为什么我可以复制,肯定会读取文件的全部内容,而不能直接读取文件?有解决方法吗?

当您打开文件时,系统会检查访问模式和共享模式。任何进程的访问模式必须与其他进程的共享模式兼容。因此,如果 A 想要阅读,其他人必须以共享模式允许阅读。写作也一样。

如果进程 A 已打开文件进行写入,而您说 SharingMode.Read 调用将失败。你在这种情况下说 "others may only read from the file, not write."

如果您指定 ShareMode.ReadWrite,则表示 "others can read or write, I don't care",如果没有其他进程指定 ShareMode.Write,则允许​​您从文件中读取。

But why I can copy, which surely reads the whole content of file

好吧,从概念上讲,它会读取整个文件,尽管它可能发生在比复制流更低的级别。在 Windows 上,它调用 CopyFileEx 系统函数,传递路径。在 *nix 系统上,它也使用系统调用,但确实使用 FileAccess.Read, FileShare.Read 为该调用打开源文件,因此您会遇到同样的问题。

while being restricted from directly reading the file?

如果一个文件可能被写入然后你不能打开它FileShare.Read因为在你正在做的各种操作之间的某个时候文件可能会被改变并且你的操作会给出错误的结果。

CopyFileEx 可以通过防止在它运行的短期内发生的任何写入影响结果来成功。无法提供更通用的形式,因为无法知道您将很快再次关闭它的流。

Is there a workaround?

解决什么问题?您无法打开流,或者您可以复制文件?对于前者,后者提供了这样的解决方法:复制文件以获取它的快照,但请注意,不能保证它。