如何在C#Winforms应用程序上使用模拟以管理员权限运行?

如何使用模拟来运行具有管理员权限的C#Winforms应用程序? 任何人都可以对此有所了解吗?

以下代码可以帮助您实现目标。 我在“代码项目”文章中找到了这个。

查看完整文章: 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: ///  /// Impersonate a windows logon. ///  public class ImpersonationUtil { ///  /// Impersonate given logon information. ///  /// Windows logon name. /// password /// domain name ///  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; } ///  /// Unimpersonate. ///  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上有一个类似的问题:
如何使用admin creds运行c#应用程序?

有一些codeproject模拟资源:
http://www.codeproject.com/KB/cs/cpimpersonation1.aspx
http://www.codeproject.com/KB/cs/zetaimpersonator.aspx

查看System.Security.Principal中的 WindowsIdentity类。

有一个Impersonate()方法可以完成你想要完成的任务。 此类缺少的链接是您必须获取访问令牌句柄才能使用它。 我知道这样做的唯一方法是通过ping一个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吗?