Kernel32.dll中的CreateFile不允许我打开物理磁盘

Dan*_*ser 5 .net c# windows pinvoke kernel32

我尝试使用下面的代码来获取MBR来自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;
}
Run Code Online (Sandbox Code Playgroud)

我试过传球

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

并且它们都不起作用.我以管理员身份运行它.我也可以\\.\C:开始工作并显示VBR而没有任何问题.

作为记录:

- 我正在运行Windows Server 2008 R2.

参考

Fré*_*idi 10

CreateFile()文档:

要成功调用,必须满足以下要求:

  • 调用者必须具有管理权限.有关更多信息,请参阅使用特殊权限运行.
  • dwCreationDisposition参数必须具有 OPEN_EXISTING标志.
  • 打开卷或软盘时,dwShareMode参数必须具有该FILE_SHARE_WRITE标志.

你可能会想尝试通过ECreationDisposition.OpenExistingdwCreationDisposition.