我以非常简单的方式使用文件上传工具。需要获取文件(非常小的大约20-25 KB)并将其传输到远程服务器。
每个服务器都可以访问特定的用户名和密码,因为我必须在使用File.SaveAs()函数之前使用Impersonation。
public void btnUploadFile_Click(Object sender, EventArgs e)
{
try
{
string strUploadDir = GetFileUploadLocation(ddlRole.SelectedItem.Value, fuupload.FileName);
objCommon.ImpersonateUser("xxxxxx","xxx", "xxx");
fuupload.SaveAs(strUploadDir + "\\" + fuupload.FileName);
objCommon.EndImpersonation();
divUploadMessage.InnerHtml = "<font color='green'><b>File uploaded successfully.</b></font><br>";
}
catch (Exception ex)
{
divUploadMessage.InnerHtml = "<font color='red'><b>Failed to upload. Please try again. Error : " + ex.ToString() + "</b></font><br>";
}
}
现在,我遇到的问题:
对于使用的模拟,下面是代码。
public bool ImpersonateUser(String userName, String domain, String password)
{
WindowsIdentity objIdentity;
IntPtr token = IntPtr.Zero;
IntPtr tokenDuplicate = IntPtr.Zero;
if (RevertToSelf())
{
if (LogonUserA(userName, domain, password, LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, ref token) != 0)
{
if (DuplicateToken(token, 2, ref tokenDuplicate) != 0)
{
objIdentity = new WindowsIdentity(tokenDuplicate);
impersonationContext = objIdentity.Impersonate();
if (impersonationContext != null)
{
CloseHandle(token);
CloseHandle(tokenDuplicate);
return true;
}
}
}
}
if (token != IntPtr.Zero)
CloseHandle(token);
if (tokenDuplicate != IntPtr.Zero)
CloseHandle(tokenDuplicate);
return false;
}