Vadym, Sorry but you got it wrong.
You don't have to write a device driver, there is one installed when you
have a SD (or MM device) installed, it comes with the OS, nor do you have to
call DeviceIoControl to read write or position the file pointer to a device.
As I said before, all you have to do is get a handle to the device by
calling CreateFile using PInvoke. The handle returned can then be used by
the framework FileStream class to read, write and seek the device, jst like
any other device in the system.
Herewith a sample that reads sector 0 of the first HD in the system.
Note that here I assume a sector length of 512 bytes, some devices may have
other sector sizes, so check the drive geometry before doing stupid things.
using System;
using System.IO;
using System.Runtime.InteropServices;
using Microsoft.Win32.SafeHandles;
using System.Security;
using System.Text;
[SuppressUnmanagedCodeSecurity]
class Tester
{
const int FILE_FLAG_NO_BUFFERING = unchecked((int)0x20000000);
const int FILE_FLAG_SEQUENTIAL_SCAN = unchecked((int)0x08000000);
[DllImport("kernel32", SetLastError = true, CharSet = CharSet.Unicode)]
static extern SafeFileHandle CreateFile(String fileName,
int
desiredAccess,
System.IO.FileShare
shareMode,
IntPtr
securityAttrs,
System.IO.FileMode
creationDisposition,
int
flagsAndAttributes,
IntPtr
templateFile);
static void Main()
{
FileStream fs;
SafeFileHandle handle;
int blockSize = 512;
int flags = FILE_FLAG_NO_BUFFERING | FILE_FLAG_SEQUENTIAL_SCAN ;
/* Call the Windows CreateFile() API to open the file */
handle = CreateFile( "\\\\.\\PHYSICALDRIVE0",
(int)FileAccess.Read,
FileShare.None,
IntPtr.Zero,
FileMode.Open,
flags,
IntPtr.Zero);
if (!handle.IsInvalid)
{
fs = new FileStream(handle, FileAccess.Read, blockSize, false);
byte[] b = new byte[blockSize];
UTF8Encoding temp = new UTF8Encoding(true);
fs.Seek(0, SeekOrigin.Begin);
fs.Read(b,0,b.Length);
Console.WriteLine(temp.GetString(b));
}
else
Console.WriteLine("Failed to open device");
}
}
Willy.
"Vadym Stetsyak" <va*****@ukr.net> wrote in message
news:OL**************@TK2MSFTNGP05.phx.gbl...
| Hello, Willy!
|
| WDM> What makes you think that using defragmentation API's would help?
|
| Defrag API is not complete solution, however it can be used to achieve the
goals that OP stated above:
| he want to write data to specific sector, that is write directly. AFAIK
to accomplish this ( direct write ) he has to write device driver.
|
| Defrag API gives the ablity to put file to the specified place on the disk
via DeviceIoControl(...FSCTL_MOVE_FILE...) flag.
|
| --
| Regards, Vadym Stetsyak
| www:
http://vadmyst.blogspot.com