2

我正在使用登录凭据访问其他服务器。我的问题是,如果我最初运行代码,它会显示错误为

Logon failure: unknown user name or bad password

但是如果我在通过命令提示符连接到服务器后尝试运行代码。然后,该应用程序工作正常,它不会抛出任何错误。因此,每天我都需要通过命令提示符连接到服务器一次,才能正常运行应用程序。

这是我的代码:

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

1 回答 1

6

找到了解决方案。请参阅更新的代码以获取答案。

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();
         }
     }
于 2012-11-02T06:03:54.143 回答