1
votes

I try to connect to another machine to save files to it using LogonUser method. This is my code:

public class ImpersonationHelper
{
    [DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
    public static extern bool LogonUser(String lpszUsername, String lpszDomain, String lpszPassword, int dwLogonType, int dwLogonProvider, ref IntPtr phToken);

    enum LogonType
    {
        Interactive = 2,
        Network = 3,
        Batch = 4,
        Service = 5,
        Unlock = 7,
        NetworkClearText = 8,
        NewCredentials = 9
    }

    enum LogonProvider
    {
        Default = 0,
        WinNT35 = 1,
        WinNT40 = 2,
        WinNT50 = 3
    }

    public IntPtr Login(string username,string password)
    {
        // machineIp
        string domain = "XXX.XX.XX.XX";
        int logonType = (int)LogonType.Network;
        int logonProvider = (int)LogonProvider.WinNT50;
        IntPtr tokenHandle = IntPtr.Zero;
        bool returnValue = LogonUser(username, domain, password, logonType, logonProvider, ref tokenHandle);
        if (!returnValue)
        {
            int nErrorCode = Marshal.GetLastWin32Error();
            throw new System.ComponentModel.Win32Exception(nErrorCode);
        }
        return tokenHandle;
    }
}

the return value of LogonUser always false and the value of Marshal.GetLastWin32Error() sometimes is 0 (means "The operation completed successfully") then 1326 (means "The user name or password is incorrect"). What is my error?

1
Shouldn't domain hold the machines name instead of the IP address?Romano Zumbé
Using the wrong arguments is the obvious failure mode. You'll first have to try to logon to the machine using Explorer. As long as that doesn't work you'll have no odds of making it work in code. Ask whomever manages that machine for help.Hans Passant

1 Answers

0
votes

Please try logon type 2->9 and provider 3 or 0.