CreateFile in Kernel32.dll returns an invalid handle

Soorya Chandrasekaran picture Soorya Chandrasekaran · May 21, 2013 · Viewed 8.4k times · Source

I'm trying to create a safe file handle for "C:" using the CreateFile method of kernel32.dll which always returns me an invalid handle.

Any help on what am i doing wrong here?"C:

CreateFile(
    lpFileName: "C:",
    dwDesiredAccess: FileAccess.ReadWrite,
    dwShareMode: FileShare.ReadWrite,
    lpSecurityAttributes: IntPtr.Zero,
    dwCreationDisposition: FileMode.OpenOrCreate,
    dwFlagsAndAttributes: FileAttributes.Normal,
    hTemplateFile: IntPtr.Zero);

[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)]
public static extern SafeFileHandle CreateFile(
    string lpFileName,
    [MarshalAs(UnmanagedType.U4)] FileAccess dwDesiredAccess,
    [MarshalAs(UnmanagedType.U4)] FileShare dwShareMode,
    IntPtr lpSecurityAttributes,
    [MarshalAs(UnmanagedType.U4)] FileMode dwCreationDisposition,
    [MarshalAs(UnmanagedType.U4)] FileAttributes dwFlagsAndAttributes,
    IntPtr hTemplateFile);

Answer

Steve picture Steve · May 21, 2013

There are a couple of parameters not quite right.

  1. To open a volume, you must prefix the drive letter with \\.\.
  2. 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.