Logon failure: unknown user name or bad password.error while accessing other server

六眼飞鱼酱① 提交于 2019-12-02 05:11:39

问题


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();
         }
     }


来源:https://stackoverflow.com/questions/13189565/logon-failure-unknown-user-name-or-bad-password-error-while-accessing-other-ser

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!