【问题标题】:CreateFile in Kernel32.dll does not allow me to open a physical diskKernel32.dll 中的 CreateFile 不允许我打开物理磁盘
【发布时间】:2010-11-26 19:24:10
【问题描述】:

我正在尝试使用以下代码从PhysicalDrive0 获取MBR

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;
}

我试过了

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

它们都不起作用。我以管理员身份运行它。我还可以让\\.\C: 正常工作并显示 VBR。

备案:

-我正在运行 Windows Server 2008 R2。

参考

【问题讨论】:

  • 您收到的 Win32 错误代码是什么?
  • 根据我使用的输入,它给了我 2 和 87。

标签: c# .net windows pinvoke kernel32


【解决方案1】:

来自CreateFile() 文档:

必须满足以下要求 让这样的调用成功:

  • 调用者必须具有管理权限。更多 信息,请参阅 Running with Special 特权
  • dwCreationDisposition 参数必须具有 OPEN_EXISTINGflag
  • 打开卷或软盘时,dwShareMode 参数必须 有FILE_SHARE_WRITE 标志。

您可能想尝试在dwCreationDisposition 中传递ECreationDisposition.OpenExisting

【讨论】:

  • 这是票!非常感谢!
猜你喜欢
  • 1970-01-01
  • 2018-04-11
  • 2015-02-13
  • 1970-01-01
  • 2013-11-16
  • 2012-12-28
  • 1970-01-01
  • 2013-02-09
  • 1970-01-01
相关资源
最近更新 更多