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 long Position() { if (DeviceApi.SetFilePointerEx(safeFileHandle, 0, out var offset, DeviceApi.EMoveMethod.Current)) { return(offset); } var error = Marshal.GetLastWin32Error(); throw new IOException($"Failed to get position, SetFilePointerEx returned Win32 error {error}"); }
public long Seek(long offset, SeekOrigin origin) { if (!Enum.TryParse <DeviceApi.EMoveMethod>(origin.ToString(), out var moveMethod)) { throw new ArgumentOutOfRangeException(nameof(origin)); } if (DeviceApi.SetFilePointerEx(safeFileHandle, offset, out var newOffset, moveMethod)) { return(newOffset); } var error = Marshal.GetLastWin32Error(); throw new IOException($"Failed to seek position offset {offset} and origin {origin}, SetFilePointerEx returned Win32 error {error}"); }