Why does DeviceIoControl throw error 21 (Device Not Ready) from C# when the equivalent in C works fine?

Posted by Ragesh on Stack Overflow See other posts from Stack Overflow or by Ragesh
Published on 2010-12-24T05:48:28Z Indexed on 2010/12/24 5:54 UTC
Read the original article Hit count: 205

Filed under:
|
|
|
|

I'm trying to send an IOCTL_SERVICE_REFRESH command to the GPS Intermediate Driver service using C# like this:

handle = CreateFile("GPD0:",
    GENERIC_READ,
    FILE_SHARE_READ | FILE_SHARE_WRITE,
    IntPtr.Zero,
    OPEN_EXISTING, 
    FILE_ATTRIBUTE_NORMAL, 
    IntPtr.Zero);

if (handle.ToInt32() == INVALID_HANDLE_VALUE)
{
    rc = Marshal.GetLastWin32Error();
    return rc;
}

int numBytesReturned = 0;

rc = DeviceIoControl(
    handle,
    IOCTL_SERVICE_REFRESH,
    null,
    0,
    null,
    0,
    ref numBytesReturned,
    IntPtr.Zero);

int error = Marshal.GetLastWin32Error();

GetLastWin32Error always gives me error 21 (device not ready). However, the equivalent call when made from C++ works fine:

HANDLE hGPS = CreateFile(L"GPD0:", GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
if (hGPS != INVALID_HANDLE_VALUE) {
  BOOL ret = DeviceIoControl(hGPS,IOCTL_SERVICE_REFRESH,0,0,0,0,0,0);
  DWORD err = GetLastError();       
}

I suspected a problem with the PInvoke signatures, but I can't seem to find anything wrong here:

[DllImport("coredll.dll", EntryPoint = "DeviceIoControl", SetLastError = true)]
public static extern int DeviceIoControl(
    IntPtr hDevice,
    uint dwIoControlCode,
    byte[] lpInBuffer,
    int nInBufferSize,
    byte[] lpOutBuffer,
    int nOutBufferSize,
    ref int lpBytesReturned,
    IntPtr lpOverlapped);

[DllImport("coredll.dll", SetLastError = true)]
public static extern IntPtr CreateFile(
    String lpFileName,
    uint dwDesiredAccess,
    uint dwShareMode,
    IntPtr attr,
    uint dwCreationDisposition,
    uint dwFlagsAndAttributes,
    IntPtr hTemplateFile);

What am I missing here?

© Stack Overflow or respective owner

Related posts about c#

Related posts about c