using directives#region Using directives
using System;
using System
using System
using System
#endregion
namespace Impersonal
{
class Program
{
測試代碼#region 測試代碼
public static void Main(string[] args)
{
Console
+ WindowsIdentity
ImpersonatedWork testDel = new ImpersonatedWork(Test);
ImpersonateAndDo(
Console
+ WindowsIdentity
}
static void Test()
{
Console
+ WindowsIdentity
}
#endregion
[DllImport(
public extern static bool LogonUser(String lpszUsername
String lpszPassword
int dwLogonProvider
[DllImport(
public extern static bool CloseHandle(IntPtr handle);
[DllImport(
public extern static bool DuplicateToken(IntPtr ExistingTokenHandle
int SECURITY_IMPERSONATION_LEVEL
public delegate void ImpersonatedWork();
/**//// <summary>
/// 以指定用戶的身份去做一件事情
/// </summary>
/// <param name=
/// <param name=
/// <param name=
public static void ImpersonateAndDo(string UserName
{
扮演用戶#region 扮演用戶
string domainName = string
string userName = string
IntPtr tokenHandle = new IntPtr(
IntPtr dupeTokenHandle = new IntPtr(
const int LOGON
const int LOGON
const int SecurityImpersonation =
if (! Regex
{
throw new ApplicationException(
}
string[] tmp = UserName
if (tmp
{
domainName = tmp[
userName = tmp[
}
else
{
userName = tmp[
}
tokenHandle = IntPtr
dupeTokenHandle = IntPtr
bool returnValue = LogonUser(userName
LOGON
ref tokenHandle);
if (!returnValue)
{
throw new ApplicationException(
}
//Console
// + WindowsIdentity
bool retVal = DuplicateToken(tokenHandle
if (!retVal)
{
CloseHandle(tokenHandle);
throw new ApplicationException(
}
WindowsIdentity newId = new WindowsIdentity(dupeTokenHandle);
WindowsImpersonationContext impersonatedUser = newId
#endregion
以新用戶身份調用#region 以新用戶身份調用
WhatToDo();
#endregion
取消扮演#region 取消扮演
impersonatedUser
if (tokenHandle != IntPtr
CloseHandle(tokenHandle);
if (dupeTokenHandle != IntPtr
CloseHandle(dupeTokenHandle);
#endregion
}
}
}
From:http://tw.wingwit.com/Article/program/net/201311/12516.html