-2

I have found a way to read from a drive, using the method posted by Darryl Braaten How do I read a disk directly with .Net?

I am now trying to find a way to write on a drive, and in his method the write method is not implemented. Anyone could suggest a way of doing it?

Thanks for your time.

Community
  • 1
  • 1
Konstantine
  • 71
  • 1
  • 9
  • Importing and using `WriteFile()` function (pretty symmetric to `ReadFile()` as used there). Don't refrain to come back if you have any issue with your code doing that... – Adriano Repetti Sep 29 '14 at 08:20
  • I get a Stream was not writable ,even thought i set the Handler to GENERIC_READ | GENERIC_WRITE, and Filestream to FileAccess.ReadWrite. Any idea why i am gettings that error? – Konstantine Sep 29 '14 at 11:53

1 Answers1

0

Just use the WriteFile P/Invoke function:

[DllImport("kernel32.dll", SetLastError=true)]
static extern bool WriteFile(
    IntPtr hFile, 
    byte[] lpBuffer, 
    uint nNumberOfBytesToWrite, 
    out uint lpNumberOfBytesWritten,
    IntPtr lpOverlapped);

Replace the ReadFile calls by WriteFile, that's pretty easy. Just keep in mind:

  • the handle you got using CreateFile has a write access
  • you have to write bytes per chunk; chunk size must be a multiple of the sector size. I.e. if you want to write only 1 byte, you'll have to read a whole sector, modify the byte in memory, and write back the whole sector
ken2k
  • 48,145
  • 10
  • 116
  • 176
  • I have setted the Handle to GENERIC_READ | GENERIC_WRITE, and Filestream FileAccess.ReadWrite, but i get a "Stream was not writable." Error. – Konstantine Sep 29 '14 at 10:08