views:

446

answers:

1

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 Marshal'ed (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,

+2  A: 

LogonUser takes an LP**T**STR, 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.

Reed Copsey
Odd thing is - when I call LoadUserProfile(...) with the token obtained from LogonUser, is it is not done with Marshalling the profile name create has unrecognized characters (those squares) when viewed from explorer - but works fine if I marshal them as shown.Odd no?
Shaitan00