本文介绍了我如何使用模拟在C#的WinForms应用程序与管理员权限运行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何使用模拟运行具有管理员权限一个C#WinForms应用程序?
任何人都可以抛出一些轻这个

How do I use impersonation to run a C# Winforms application with admin privileges? Can anyone throw some light on this?

推荐答案

下面的代码行可以帮你实现你?功能:该我发现形成CP的文章

Following line of code may help you to achieve you function : which i found form the cp article

查看全文:

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;
}

这篇关于我如何使用模拟在C#的WinForms应用程序与管理员权限运行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-29 17:53