Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read the contents of an entire disk bit by bit

Tags:

c++

c#

I've got a flash card that I need to compute a checksum on the entire contents of the drive.

If I could acquire a stream to the entire drive I could just read it in bit by bit.

Does anyone know if there is an API for doing this?

Everything I see so far requires me to open a file.

Is there any way to just read an entire drive's contents bit by bit?

like image 757
user1090205 Avatar asked Feb 23 '12 17:02

user1090205


2 Answers

If you want to write C# code, then you'll have to use P/Invoke to read data from your disk (RAW access).

Is there any way to just read an entire drive's contents bit by bit?

You'll have to make a difference between the drive (logical representation of your flash card, with a FileSystem installed on it, specified by the drive letter) and the disk (physical representation of your flash card, specified by the disk number).

See my previous answer about how to read RAW data from a drive/disk:

Basically, you'll first need a handle to the disk/drive:

// For a DISK:
IntPtr hDisk = CreateFile(string.Format("\\\\.\\PhysicalDrive{0}", diskNumber),
    GenericRead,
    Read | Write,
    0,
    OpenExisting,
    0,
    IntPtr.Zero);

// For a DRIVE
IntPtr hDrive = NativeMethods.CreateFile(
    string.Format("\\\\.\\{0}:", DriveLetter)
    GenericRead,
    Read | Write,
    IntPtr.Zero,
    OpenExisting,
    0,
    IntPtr.Zero);

Then use SetFilePointerEx (so you can move the offset where you want to read), ReadFile (fills a buffer with bytes read from the disk/drive), CloseHandle (closes the handle opened by CreateFile).

Read the disk/drive by chunks (so basically, a loop from offset "0" to offset "disk/drive size").

What's important (or ReadFile will always fail): the size of read chunks must be a multiple of the sector size of your disk (512 bytes generally).

like image 153
ken2k Avatar answered Nov 15 '22 07:11

ken2k


I'm not sure if there is direct support for this in .NET, but you can use Platform Invoke to call the Win32 API functions. CreateFile() should be your starting point, as it allows you to get a handle to the physical drive:

You can use the CreateFile function to open a physical disk drive or a volume, which returns a direct access storage device (DASD) handle that can be used with the DeviceIoControl function. This enables you to access the disk or volume directly, for example such disk metadata as the partition table.

The documentation informs you of restrictions (such as requiring administrative privileges) and hints at how to get a physical drive number from the volume letter, etc.

like image 43
André Caron Avatar answered Nov 15 '22 05:11

André Caron