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.
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 theOPEN_EXISTING
flag.- When opening a volume or floppy disk, the
dwShareMode
parameter must have theFILE_SHARE_WRITE
flag.
You might want to try passing ECreationDisposition.OpenExisting
in dwCreationDisposition
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With