开发者

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

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

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

  • MSDN: CreateFile function
  • MSDN: Naming Files, Paths, and Namespaces


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜