日期:2014-05-17 浏览次数:20528 次
[DllImport("advapi32.dll", SetLastError = true)]
private static extern bool LogonUser(string
lpszUsername, string lpszDomain, string lpszPassword,
int dwLogonType, int dwLogonProvider, ref IntPtr phToken);
[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern bool CloseHandle(IntPtr handle);
[DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
public extern static bool DuplicateToken(IntPtr existingTokenHandle,
int SECURITY_IMPERSONATION_LEVEL, ref IntPtr duplicateTokenHandle);
// logon types
const int LOGON32_LOGON_INTERACTIVE = 2;
const int LOGON32_LOGON_NETWORK = 3;
const int LOGON32_LOGON_NEW_CREDENTIALS = 9;
// logon providers
const int LOGON32_PROVIDER_DEFAULT = 0;
const int LOGON32_PROVIDER_WINNT50 = 3;
const int LOGON32_PROVIDER_WINNT40 = 2;
const int LOGON32_PROVIDER_WINNT35 = 1;
static string HelpUserName = System.Configuration.ConfigurationManager.AppSettings["HelpUserName"];
static string HelpDomain = System.Configuration.ConfigurationManager.AppSettings["HelpDomain"];
static string HelpPassword = System.Configuration.ConfigurationManager.AppSettings["HelpPassword"];
static string HelpFilePath = System.Configuration.ConfigurationManager.AppSettings["HelpFilePath"];
public static byte[] GetFile(string DownFileName)
{
byte[] DownloadFile = null;//要下载的文件的数据
IntPtr tokenHandle = new IntPtr(0);
IntPtr dupeTokenHandle = new IntPtr(0);
tokenHandle = IntPtr.Zero;
bool returnValue = LogonUser(HelpUserName, HelpDomain, HelpPassword, LOGON32_LOGON_NEW_CREDENTIALS, LOGON32_PROVIDER_DEFAULT, ref tokenHandle);
if (returnValue == false)
{
int ret = Marshal.GetLastWin32Error();
throw new System.ComponentModel.Win32Exception(ret);
}
WindowsIdentity newId = null;
WindowsImpersonationContext impersonatedUser = null;
using (newId = new WindowsIdentity(tokenHandle))
{
using (impersonatedUser = newId.Impersonate())
{//操作文档
string filePath = HelpFilePath + "\\" + DownFileName;//图片存放路径
DownloadFile = File.ReadAllBytes(filePath);//获取文件数据
}
}
impersonatedUser.Undo();
if (tokenHandle != IntPtr.Zero)
CloseHandle(tokenHandle);
return DownloadFile;
}