"Kid" <Ki*@discussion s.microsoft.com wrote in message
news:37******** *************** ***********@mic rosoft.com...
hi
Can I CreateFile and DeviceIOControl by C# ?
Yes, by using PInvoke.
Does it use the same functions as Visual C , what file should I include
and
link ?
There is nothing to link or include, you need to declare the function in C#,
the runtime will dynamically load and call the function from the DLL.
As an example, following are the PInvoke declarations (C#) for the
kernel32.dll API's CreateFile, DeviceIoControl and CloseHandle.
[DllImport("kern el32.dll", CharSet = CharSet.Auto,
SetLastError=tr ue)]
static extern SafeFileHandle CreateFile(stri ng lpFileName, int
dwDesiredAccess , int dwShareMode,
IntPtr lpSecurityAttri butes, uint dwCreationDispo sition, uint
dwFlagsAndAttri butes,
SafeFileHandle hTemplateFile);
[DllImport("kern el32.dll", CharSet = CharSet.Auto, SetLastError =
true)]
static extern int DeviceIoControl (SafeFileHandle handle, uint
dwIoControlCode , IntPtr lpInBuffer,
int nInBufferSize, IntPtr lpOutBuffer, int nOutBufferSize,
out int lpBytesReturned , IntPtr lpOverlapped);
[DllImport("kern el32.dll")]
static extern bool CloseHandle(Int Ptr hObject);
note that you also need to declare all of the constants used as argument in
an API call, for instance:
const int GENERIC_READ = unchecked((int) 0x80000000);
const int GENERIC_WRITE = unchecked((int) 0x40000000);
..
const int OPEN_EXISTING = 3;
In short you need to convert the header file contents related to the API you
want to use into C# style declarations.
When you are done with all this, you can call these from C# just like this:
SafeFileHandle h = CreateFile("\\\ \.\\PhysicalDri ve1", GENERIC_READ, ...);
You may want to consult the PInvoke site here <http://www.pinvoke.net/>
before you start to declare some API's yourself, but watch out, some API's
are declared incorrectly, some are missing the structs constant or enum
declarations, and a large deal is simply covered by managed API's.
Willy.