Benoit
Benoit

Reputation: 79185

How can CreateFile fail with FILE_SHARE_READ and succeed with FILE_SHARE_READ|FILE_SHARE_WRITE|FILE_SHARE_DELETE?

Try it yourself:

Create an XLS file, open it in Excel.

Open sysinternals Process Monitor, and watch what happens while you make a copy of your XLS file in the explorer (just hit ctrl-c ctrl-v).

Two calls to ::CreateProcess in a row. First call asks for read permissions, and gets Access denied. Second call asks for read plus write plus delete and passes.

Is that normal?

Upvotes: 6

Views: 8567

Answers (2)

Luke
Luke

Reputation: 11421

You have to use compatible sharing modes. If Excel opens the file with FILE_SHARE_READ | FILE_SHARE_WRITE then subsequent attempts to open the file must use at least those same flags. Specifically from the MSDN documentation on CreateFile:

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.

Upvotes: 3

Erik
Erik

Reputation: 91270

If you open a file with FILE_SHARE_READ you're saying you're willing to share access to this file, but only for reads.

If you open with all the flags, you're willing to share access also for writes/delete.

FILE_SHARE_READ is more restrictive than FILE_SHARE_READ|FILE_SHARE_WRITE|FILE_SHARE_DELETE

If some other process (excel) has this file opened for e.g. write (and it has the sharing flags set), the only way you can access it is to accept sharing it for write.

Upvotes: 12

Related Questions