Search code examples
filewinapifile-locking

Change CreateFileW dwShareMode


Is there a way to use CreateFileW and with FILE_SHARE_WRITE and then after a while change that to only FILE_SHARE_READ?

I could not find any documentation, but it seems memory map files can elevate permissions, so I guess maybe there is a way for opening a file, just to read, and then lock it for write.


Solution

  • Permissions and sharing conflicts are checked when a file is opened. So if you want to have a more restrictive sharing more (change from FILE_SHARE_WRITE | FILE_SHARE_READ to only FILE_SHARE_READ) you need to go through that process again.

    Be prepared for your CreateFile to fail since there can be a handle open with write access.

    Locking can be done without reopening the file, but those locks are cooperative/voluntary (and lock operations can also fail).