Logon failure: unknown user name or bad password.e

2019-07-20 09:03发布

问题:

I'm accessing other server with the login credentials. My problem is if I run the code initially, it wil show the error as

Logon failure: unknown user name or bad password

but if I try running the code after connecting to the server once through the command prompt. Then, the application works fine and it does not throw any error. So, daily I need to connect to server once through command prompt in order to run the application without errors.

Here is my code:

static void main()
{
  string sourceDir = "//server.domain.mhc//drive";
                string DestinationDir = "D:\\Test";

                DirectoryCopy(sourceDir, DestinationDir, true);
}

[DllImport("advapi32.DLL", SetLastError = true)]
public static extern int LogonUser(string lpszUsername, string lpszDomain, string lpszPassword, int dwLogonType, int dwLogonProvider, ref IntPtr phToken);

private static void DirectoryCopy(string sourceDirName, string destDirName, bool copySubDirs)
{
    clsEmail objEmail = new clsEmail();
    try
    {
        IntPtr admin_token = default(IntPtr);
        if(LogonUser("myusername","domain","pwd",9,0,ref admin_token) != 0)
        {
            DirectoryInfo dir = new DirectoryInfo(sourceDirName);
            DirectoryInfo[] dirs = dir.GetDirectories();
        }

回答1:

Found out the solution. See the updated code for the answer.

try
     {
        IntPtr admin_token = default(IntPtr);
        //Added these 3 lines
        WindowsIdentity wid_current = WindowsIdentity.GetCurrent();
        WindowsIdentity wid_admin = null;
        WindowsImpersonationContext wic = null;


        if(LogonUser("myusername","domain","pwd",9,0,ref admin_token) != 0)
        {
        //Newly added lines
         wid_admin = new WindowsIdentity(admin_token);
         wic = wid_admin.Impersonate();

         DirectoryInfo dir = new DirectoryInfo(sourceDirName);
         DirectoryInfo[] dirs = dir.GetDirectories();
         }
     }