CreateFile in Kernel32.dll does not allow me to open a physical disk
Asked Answered
S

1

5

I am trying to use the following code to get the MBR from PhysicalDrive0:

private static byte[] ReadMbr(string lpFileName)
{
   byte[] mbr = new byte[512];

   using (SafeFileHandle drive = CreateFile(
         lpFileName: lpFileName,
         dwDesiredAccess: (uint) EFileAccess.GenericRead, //DO NOT MODIFY THE MBR!!!
         dwShareMode: (uint)EFileShare.Write | (uint)EFileShare.Read | (uint)EFileShare.Delete,
         SecurityAttributes: IntPtr.Zero,
         dwCreationDisposition: (uint) ECreationDisposition.OpenAlways,
         dwFlagsAndAttributes: (uint)EFileAttributes.System,
         hTemplateFile: IntPtr.Zero))
   {
      if (drive.IsInvalid)
         throw new IOException("Unable to access drive. Win32 Error Code " + Marshal.GetLastWin32Error());

      //Get the 1st 512 bytes of the volume (MBR)
      using (FileStream stream = new FileStream(drive, FileAccess.Read))
      {
         stream.Read(mbr, 0, 512);
      }
   }

   return mbr;
}

I have tried passing

  • \\.\PhysicalDisk0
  • \\.\PhysicalDrive0
  • \\.\PhysicalDisk0:
  • \\.\PhysicalDrive0

and none of them work. I am running it as administrator. I can also get \\.\C: to work and display the VBR without any issues.

For the record:

-I am running Windows Server 2008 R2.

References

Singularity answered 26/11, 2010 at 19:24 Comment(2)
What's the Win32 error code you receive?Pawn
It was giving me a 2 and an 87 depending on what input I was using.Singularity
U
10

From the CreateFile() documentation:

The following requirements must be met for such a call to succeed:

  • The caller must have administrative privileges. For more information, see Running with Special Privileges.
  • The dwCreationDisposition parameter must have the OPEN_EXISTING flag.
  • When opening a volume or floppy disk, the dwShareMode parameter must have the FILE_SHARE_WRITE flag.

You might want to try passing ECreationDisposition.OpenExisting in dwCreationDisposition.

Unwashed answered 26/11, 2010 at 21:16 Comment(1)
This was the ticket! Thank you so much!Singularity

© 2022 - 2024 — McMap. All rights reserved.