File.OpenRead, FileShare issues

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 IOException:

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.
It 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. Here’s a good explanation by Darin Dimitrov from 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.

5 Comments

  1. Eugeny

    Thanks a lot. That saved me a lot of debugging time.

  2. Tom

    Your Article is very helpful for me. Thank you. (from Japan)

  3. […] Today’s debugging adventure involved an ActiveX control that uses FileSystemWatcher to watch for files to be copied into a folder and then spits out some log messages onto the page. The behavior I was seeing was that sometimes when I copied a valid file into the watched folder, Internet Explorer would crash. After putting in additional logging, I found that the code was throwing an IOException. Searching for how to really open a file read-only, I learned about the FileShare parameter. […]

  4. malloc

    Thank you very much 🙂

  5. Mark Landry

    Well done. Very helpful!