public static void Read(uint volume, Int64 address, uint length, byte[] data) { // try to open the current physical drive SafeFileHandle hndl = DeviceApi.CreateFile(string.Format("\\\\.\\PhysicalDrive{0}", volume), DeviceApi.GENERIC_READ, DeviceApi.FILE_SHARE_READ | DeviceApi.FILE_SHARE_WRITE, IntPtr.Zero, DeviceApi.OPEN_EXISTING, DeviceApi.FILE_ATTRIBUTE_READONLY, IntPtr.Zero); if (!hndl.IsInvalid) { // set the file pointer to the requested address if (DeviceApi.SetFilePointerEx(hndl, address, out _, DeviceApi.EMoveMethod.Begin)) { // read the requested data from the physical drive uint dummy; if (!DeviceApi.ReadFile(hndl, data, length, out dummy, IntPtr.Zero)) { throw new System.IO.IOException("\"ReadFile\" API call failed"); } } else { throw new System.IO.IOException("\"SetFilePointerEx\" API call failed"); } hndl.Close(); } }
public uint Read(byte[] buffer) { if (DeviceApi.ReadFile(safeFileHandle, buffer, Convert.ToUInt32(buffer.Length), out var bytesRead, IntPtr.Zero)) { return(bytesRead); } var error = Marshal.GetLastWin32Error(); throw new IOException($"Failed to ReadFile returned Win32 error {error}"); }