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();
}
此代碼位於directorycopy()函數內部。希望這有助於某人。 :) – sachin
對於將來的讀者,確保在完成它們時處置WindowsIdentity和ImpersonationContext。無論是在最後的聲明中,還是更好地利用這些資源的某些「使用」塊來重構這一點。 – HodlDwon
@sachin:我遇到了同樣的問題,從不同的域複製文件,它的工作原理。 –