c# - 访问其他服务器时登录失败: unknown user name or bad password.错误

标签 c# console-application .net

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

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

最佳答案

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

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

关于c# - 访问其他服务器时登录失败: unknown user name or bad password.错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13189565/

相关文章:

c# - 处理字节数组中的非 UTF-8 字符

c# - 在字典中使用对象作为键

C# 控制台应用程序 httpWebRequest

c# - SetConsoleMode 失败并为零,lasterror = 0

.net - 同步上下文的切换是否意味着工作将在拥有同步上下文的线程上运行?

javascript - 在 AspNetCore 中使用 Rotativa 将 Html 转换为 Pdf

c# - XNA 2d 街机游戏 Sprite 跟随

java - 执行jar文件时是否可以显示控制台?

.net - WPF 窗口对接

.NET 资源泄漏陷阱