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);
There are a couple of parameters not quite right.
\\.\
.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.