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