user4437649
user4437649

Reputation:

Using CreateFile To Access a Drive Partition

I have admin rights and have no problem getting a valid handle and ultimately reading an entire hard drive via:

IntPtr handle = CreateFile(@"\\.\PHYSICALDRIVE1", GENERIC_READ, FILE_SHARE_READ, 0, OPEN_EXISTING, 0, 0);

I can also get a valid handle when I try to open a directory of that drive:

IntPtr handle = CreateFile(@"\\.\Z:\\", GENERIC_READ, FILE_SHARE_READ, 0, OPEN_EXISTING, 0, 0);

But I cannot get a valid handle when I try to simply open a partition of that drive:

IntPtr handle = CreateFile(@"\\.\Z:", GENERIC_READ, FILE_SHARE_READ, 0, OPEN_EXISTING, 0, 0);

GetLastWin32Error returns access denied (5).

Of course if I offline the drive, then I get "The system cannot find the file specified." I've tried everything I could think of with different partitions, different options etc. to no available.

Upvotes: 3

Views: 4050

Answers (2)

Edward Severinsen
Edward Severinsen

Reputation: 101

I would like to point out that the documentation of CreateFile says the following about FILE_SHARE_WRITE:

Enables subsequent open operations on a file or device to request write access.

Otherwise, other processes cannot open the file or device if they request write access.

If this flag is not specified, but the file or device has been opened for write access or has a file mapping with write access, the function fails.

Upvotes: 2

user4437649
user4437649

Reputation:

I found the answer myself. Let me correct myself in pointing out that CreateFile(@"\.\Z:" is opening a Volume, not necessarily a partition. However, I could not even open a volume.

Until I added FILE_SHARE_WRITE to the options as follows:

IntPtr handle = CreateFile(@"\.\Z:", GENERIC_READ, FILE_SHARE_WRITE | FILE_SHARE_READ, 0, OPEN_EXISTING, 0, 0);

That was the key to getting a valid handle. This is certainly not intuitive!

Why this should be the case is only known by Microsoft I guess.

Upvotes: 3

Related Questions