There are a couple of parameters not quite right.
- To open a volume, you must prefix the drive letter with
\\.\
. - You can only open the volume with read privileges.
Try this code:
SafeFileHandle handle = CreateFile(
lpFileName: @"\\.\C:",
dwDesiredAccess: FileAccess.Read,
dwShareMode: FileShare.ReadWrite,
lpSecurityAttributes: IntPtr.Zero,
dwCreationDisposition: FileMode.OpenOrCreate,
dwFlagsAndAttributes: FileAttributes.Normal,
hTemplateFile: IntPtr.Zero );
Note that to open a volume handle with read privileges, you must be running as an administrator, otherwise you will get access denied (error code 5). As Nik Bougalis and the CreateFile documentation points out, if you specify dwDesiredAccess
as 0 administrator privileges are not required.
If this parameter is zero, the application can query certain metadata such as file, directory, or device attributes without accessing that file or device, even if GENERIC_READ access would have been denied.