C# – wrong with the DLLImport of LogonUser with String Marshaling? [C#]

cdllimportmarshalling

For some odd reason, when I marshal the LogonUser DLLImport parameters I am no longer able to login succesfully when using the INTERACTIVE logon type, it works for NETWORK logon type.

This is my code:

    [DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
    public static extern bool LogonUser
        (
        [MarshalAs(UnmanagedType.LPStr)]
        String lpszUsername,
        [MarshalAs(UnmanagedType.LPStr)]
        String lpszDomain,
        [MarshalAs(UnmanagedType.LPStr)]
        String lpszPassword,
        int dwLogonType,
        int dwLogonProvider,
        out IntPtr hToken
        );

    bResult = LogonUser(
        "username",
        ".",
        "password",
        (int)LogonType.INTERACTIVE,     // = 2
        (int)LogonProvider.DEFAULT,     // = 0
        out hToken
        );

Now, as-is my call to LogonUser fails (Logon Exception: Logon failure: unknown user name or bad password), but if I remove the [MarshalAs(UnmanagedType.LPStr)]s from the DLLImport it works fine, also if I switch to LogonType.NETWORK it works fine, why is it different with INTERACTIVE?

Sadly I need to keep it as I use this with other functions such as LoadUserProfile that needs it to be Marshalled (only way I could get it to work and not display unknown windows characters [squares]). Do I need to do some funky marshaling of strings or something to get it to validate correctly?

Any help would be appreciated.
Thanks,

Best Answer

LogonUser takes an LPTSTR, not an LPSTR, as parameters. You should just use the default string marshaling, and it will work correctly.

See LogonUser and pinvoke.net's declaration for a property P/Invoke of LogonUser.

Related Topic