Question

I'm trying to prevent a third-party DLL in my process from reading a file I've opened, and I've found it to be... well, impossible.

No matter what I do, no matter what share flags I specify, their call always seems to succeed!

Here is the screenshot from Process Monitor -- the first CreateFile call is mine, and the rest are theirs:

Screenshot

How is this even possible? Why is the "Share Mode: None" lying to me, and how can I prevent this?


This code below is an example that reproduces the problem:

#include <stdio.h>
#include <Windows.h>

int main()
{
    LPCTSTR file = TEXT("C:\\Test1234.xml");
    HANDLE hFile1 =
        CreateFile(file, FILE_READ_ATTRIBUTES, 0, NULL, OPEN_ALWAYS, 0, NULL);
    HANDLE hFile2 =
        CreateFile(file, FILE_READ_DATA, 0, NULL, OPEN_ALWAYS, 0, NULL);
    DWORD n;
    BYTE buf[1];
    printf("%d\n", ReadFile(hFile2, buf, sizeof(buf), &n, NULL));
    CloseHandle(hFile1);
    CloseHandle(hFile2);
    DeleteFile(file);
}
Was it helpful?

Solution

Share modes are enforced for actually reading and writing the DATA of the file. Attributes (like file size, timestamps, etc) are not covered by the sharing rules and there is no way to prevent their access short of ACLs.

The best you can to is open the file for R/W/D access and not specify SHARE_READ|WRITE|DELETE.

Weird, but true.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top