user932741
user932741

Reputation: 21

CreateFile in C#

I am using CreateFile function to create HID Device Handle. Below is sample code. After executing the code, I am always getting HidHandle value -1, which it should not be. Any suggestions please.

public int CreateFile(string FileName)
{
    HidHandle = CreateFile(FileName,GENERIC_READ | GENERIC_WRITE,
        FILE_SHARE_READ | FILE_SHARE_WRITE,0,OPEN_EXISTING,0,0);           
}

 [DllImport("kernel32.dll", SetLastError = true)]
    private static extern int CreateFile(
        string lpFileName,                          
        uint dwDesiredAccess,                       
        uint dwShareMode,                           
        uint lpSecurityAttributes,              
        uint dwCreationDisposition,                 
        uint dwFlagsAndAttributes,                  
        uint hTemplateFile                          
        );

Calling GetLastWin32Error() returns the value 5.

Upvotes: 1

Views: 8196

Answers (3)

user3409863
user3409863

Reputation: 43

CreateFile is not an exported function from kernel32.dll kernel32.dll exports either CreateFileW or CreateFileA

You should use

[DllImport("kernel32.dll", SetLastError = true)] private static extern int CreateFileW( [MarshalAs(UnmanagedType.LPWStr)] string lpFileName,
uint dwDesiredAccess,
uint dwShareMode,
IntPtr lpSecurityAttributes,
uint dwCreationDisposition,
uint dwFlagsAndAttributes,
IntPtr hTemplateFile
);

Upvotes: 0

Irfy
Irfy

Reputation: 2521

try changing that to

public int CreateFile(string FileName)
{
  return CreateFile(FileName,GENERIC_READ | GENERIC_WRITE,
       FILE_SHARE_READ | FILE_SHARE_WRITE,0,OPEN_EXISTING,0,0);           
}

Upvotes: 1

David Heffernan
David Heffernan

Reputation: 612993

CreateFile is returning INVALID_HANDLE_VALUE which indicates failure. You then call GetLastWin32Error() which returns 5. This is ERROR_ACCESS_DENIED. In other words, your process does not have sufficient rights to open that file.

Upvotes: 4

Related Questions