How to create a file mapping that allows others to open the file in exclusive mode?

Raymond Chen

A customer had a tool that opens files like DLLs and TLBs in order to extract information from them.

We currently use Create­File, Create­File­Mapping, and Map­View­Of­File to access the file. The problem is that the Create­File­Mapping prevents the file from being renamed or deleted, even if the Create­File opened the file with a sharing mode that permits those operations. It is our understanding that this is expected behavior.

Since DLLs and TLBs under active development are frequently deleted or overwritten, our use of Create­File­Mapping interferes with developer workflow because the user’s build will fail with a sharing violation. We were wondering if there is an alternative to Create­File­Mapping that would allow the file to be renamed, deleted, or written to. We know that we could slurp the entire file into memory and operate on the in-memory copy, but we were hoping for something less drastic.

Yes, there is something less drastic. In fact, this is the type of scenarios for which opportunistic locks were created: You want to access a file, but you don’t want your access to interfere with anybody else who wants to access the file after you get access.

For a code sample, I defer to my earlier discussion of opportunistic locks.

0 comments

Discussion is closed.

Feedback usabilla icon