【发布时间】:2011-03-01 12:17:15
【问题描述】:
如何使用模拟以管理员权限运行 C# Winforms 应用程序? 任何人都可以对此有所了解吗?
【问题讨论】:
标签: c#
如何使用模拟以管理员权限运行 C# Winforms 应用程序? 任何人都可以对此有所了解吗?
【问题讨论】:
标签: c#
以下代码行可能会帮助您实现目标。我在“代码项目”文章中发现了这一点。
查看全文:http://www.codeproject.com/KB/dotnet/UserImpersonationInNET.aspx
using System.Security.Principal;
using System.Runtime.InteropServices;
//the following code executed before you perform your task
if ( ! ImpersonationUtil.Impersonate( _userName, _password, _domain ) )
{
MessageBox.Show("Impersonation failed.");
return;
}
//Perform task as this user here...
//After your task, do this:
ImpersonationUtil.UnImpersonate();
Here is the code for the ImpersonationUtil class:
/// <summary>
/// Impersonate a windows logon.
/// </summary>
public class ImpersonationUtil {
/// <summary>
/// Impersonate given logon information.
/// </summary>
/// <param name="logon">Windows logon name.</param>
/// <param name="password">password</param>
/// <param name="domain">domain name</param>
/// <returns></returns>
public static bool Impersonate( string logon, string password, string
domain ) {
WindowsIdentity tempWindowsIdentity;
IntPtr token = IntPtr.Zero;
IntPtr tokenDuplicate = IntPtr.Zero;
if( LogonUser( logon, domain, password, LOGON32_LOGON_INTERACTIVE,
LOGON32_PROVIDER_DEFAULT, ref token) != 0 ) {
if ( DuplicateToken( token, 2, ref tokenDuplicate ) != 0 ) {
tempWindowsIdentity = new WindowsIdentity(tokenDuplicate);
impersonationContext = tempWindowsIdentity.Impersonate();
if ( null != impersonationContext ) return true;
}
}
return false;
}
/// <summary>
/// Unimpersonate.
/// </summary>
public static void UnImpersonate() {
impersonationContext.Undo();
}
[DllImport("advapi32.dll", CharSet=CharSet.Auto)]
public static extern int LogonUser(
string lpszUserName,
String lpszDomain,
String lpszPassword,
int dwLogonType,
int dwLogonProvider,
ref IntPtr phToken );
[DllImport("advapi32.dll",
CharSet=System.Runtime.InteropServices.CharSet.Aut o,
SetLastError=true)]
public extern static int DuplicateToken(
IntPtr hToken,
int impersonationLevel,
ref IntPtr hNewToken );
private const int LOGON32_LOGON_INTERACTIVE = 2;
private const int LOGON32_LOGON_NETWORK_CLEARTEXT = 4;
private const int LOGON32_PROVIDER_DEFAULT = 0;
private static WindowsImpersonationContext impersonationContext;
}
【讨论】:
在SO上有一个类似的问题:
How to run c# application with admin creds?
有一些codeproject模拟资源:
http://www.codeproject.com/KB/cs/cpimpersonation1.aspx
http://www.codeproject.com/KB/cs/zetaimpersonator.aspx
查看 System.Security.Principal 中的 WindowsIdentity 类。
有一个 Impersonate() 方法可以做你想做的事 完成。这个类的缺失环节是你必须获得一个 访问令牌句柄以使用它。我知道这样做的唯一方法是 调用 Win32 安全功能之一,例如 LogonUser()。
来源:
http://www.developmentnow.com/g/36_2005_4_0_0_511838/Run-with-Administrator-Credentials.htm
您还可以在应用程序清单中设置特殊的 XML,这将强制您的应用程序始终以管理员身份运行。
http://www.enusbaum.com/blog/2007/08/26/how-to-run-your-c-application-as-administrator-in-windows-vista/
【讨论】:
如果您只是想要“以管理员身份运行”,您也许可以使用RunElevated?
【讨论】: