Domanda

I am trying to invoke the CreateFile method from Kernel32.dll in a C# application, and it is returning an invalid handle everytime. I've looked all over and can't find a solution to this problem. Here is the relevant code:

Constants:

    const UInt64 GENERIC_READ = 0x80000000L;
    const UInt64 GENERIC_WRITE = 0x40000000L;
    const UInt64 GENERIC_EXECUTE = 0x20000000L;
    const UInt64 GENERIC_ALL = 0x10000000L;
    const uint FILE_SHARE_READ = 0x00000001; 
    const uint FILE_SHARE_WRITE = 0x00000002;
    const uint OPEN_EXISTING = 0x00000003;
    const uint FILE_FLAG_DELETE_ON_CLOSE = 0x04000000;

Importing the Method:

[DllImport("kernel32.dll", SetLastError = true)]
    static extern unsafe SafeFileHandle CreateFile(
          string FileName,                   
          ulong DesiredAccess,                
          uint ShareMode,                    
          IntPtr SecurityAttributes,            
          uint CreationDisposition,           
          uint FlagsAndAttributes,            
          IntPtr hTemplateFile                   
          );
SafeFileHandle JFifoDrv = LoadDriver();

Method to Load Driver:

unsafe private SafeFileHandle LoadDriver()
    {
        SafeFileHandle hDrv = (SafeFileHandle)null;
        try
        {
            hDrv = CreateFile("\\\\.\\JFIFODRV",
                GENERIC_READ | GENERIC_WRITE,
                FILE_SHARE_READ | FILE_SHARE_WRITE,
                (IntPtr)null,
                OPEN_EXISTING,
                FILE_FLAG_DELETE_ON_CLOSE,
                (IntPtr)null);

            DriverLoaded = true;
        }
        catch
        {
            poll.Stop();
            DriverLoaded = false;
        }

        return hDrv;
    }

Can Anyone help me figure out the problem?

È stato utile?

Soluzione

Your declaration is wrong, the 2nd argument is an uint, not an ulong. The pinvoke.net website is a decent source for declarations. Be sure to throw Win32Exception when JFifoDrv.IsInvalid is true.

Altri suggerimenti

I'm pretty sure that "\\\\.\\JFIFODRV" is an invalid device name, and it is certainly not a valid file name. Something like "\\\\.\\F:" should open the F: drive / partition, although I'm pretty sure this will fail if F: is mounted, as you are asking for write access.

What are you trying to open?

Also you should call Marshal.GetLastWin32Error - this will get an error code with more detail than just "it didn't work".

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top