9

I want to be able to read and write data directly to and from a disk (i.e. at a sector / cluster level) but I've yet to find a suitable tool for doing this under windows.

I've been trying to figure out how to write my own in C#, but the documentation I've found is sparse and only deals with C++ APIs.

Whats the best way of reading /writing directly to / from a drive in C#? (or can anyone recommend me a tool that allows me to read / write directly from a drive?)

Justin
  • 84,773
  • 49
  • 224
  • 367

3 Answers3

10

pinvoke.net has a collection of managed code wrappers for essentially all Win32 API's, including those that can talk to the Disk Manager service and perform low level kernel/IO.

Jason
  • 28,040
  • 10
  • 64
  • 64
  • 3
    +1 To be more specific, the right function is `CreateFile` in kernel32. There is a managed stream wrapper example here: [How do I read a disk directly with .NET](http://stackoverflow.com/questions/38190/how-do-i-read-a-disk-directly-with-net/38275#38275). – vgru Apr 20 '11 at 08:13
3

Honestly, you probably need to look at Platform Invoke if you want to write this code in C#. It lets you interact with unmanaged platform APIs, which you mentioned is the bulk of the information you've found so far :-)

Joel Martinez
  • 46,929
  • 26
  • 130
  • 185
1

This question comes up on a search for terms related to block device write in .NET, so I'd like to embellish the original answers with some direct links.

First, you'll be using a PInvoke to CreateFile to get a file handle.

PInvoke methods are used to import CreateFile into the .NET environment. MSDN have an example under their discussion of SafeFileHandle. If you want to create c# type for the parameters and return codes of CreateFile, there are some examples on PInvoke

However, you need to decide whether you want to write to physical device or a volume on it. Volumes correspond to partitions on the device. E.g. "\.\PhysicalDrive0" is the physical device, whereas "\.\C:" is the volume.

For details of the the available Win32 devices, use a C# version of QueryDosDevice Background on these Win32 devices, their naming convertion and relationship to O/S objects can be found in "Windows Internals" by Mark Russinovich.

Donal Lafferty
  • 5,807
  • 7
  • 43
  • 60