File.OpenRead, FileShare issues
Apr 20 2010 · .NET Platform
The following piece of C# code to open a file for reading (an MS Word document, opened by Word), generated an IOException.
FileStream fs = System.IO.File.OpenRead(oldFullPath);
The process cannot access the file ... because it is being used by another process.
Not too unusual, but curiously, the following code, to do the same same thing, did not generate any exceptions and the file was read successfully.
FileStream fs = System.IO.File.Open(oldFullPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
I’d always assumed that File.OpenRead was equivalent to the File.Open call above. Bad assumption. Looks like the FileShare flag is set to FileShare.Read not FileShare.ReadWrite by File.OpenRead.
Note that the FileShare flag is a bit misleading as described by the docs, it doesn’t only apply to subsequent operations. A good explanation by Darin Dimitrov on stackoverflow:
In the case of future openers, a FileShare.Read means “future openers can open the file for reading”. In the case of past openers, FileShare.Read means “open this file for me only if it has past openers that opened it for reading only”. That’s why FileShare.ReadWrite needs to be used here, because Excel opens the file for writing.