C# Process类在程序中实现以管理员方式运行外部进程运行

var process = new Process
{
    StartInfo =
    {
        WorkingDirectory = AppDomain.CurrentDomain.BaseDirectory,
        UseShellExecute = true,
        FileName = 'xxx.exe',
        CreateNoWindow = true,
        Verb = "runas"
    }
};
process.Start();

[WorkingDirectory]外部启动程序运行路径
[Verb]"runas"强调运行方式

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
C#程序请求管理员权限可以通过在app.manifest文件设置请求管理员权限,或者使用代码请求管理员权限。 方法一:在app.manifest文件设置请求管理员权限 在项目的app.manifest文件,找到下面的代码块,并将requestedExecutionLevel的level属性设置为requireAdministrator。 ```xml <requestedExecutionLevel level="requireAdministrator" uiAccess="false" /> ``` 方法二:使用代码请求管理员权限 使用代码请求管理员权限需要使用Windows API函数,可以使用下面的代码: ```csharp using System; using System.Diagnostics; using System.Runtime.InteropServices; namespace AdminLauncher { class Program { [DllImport("user32.dll", SetLastError = true)] private static extern bool ShowWindow(IntPtr hWnd, int nCmdShow); [DllImport("kernel32.dll", SetLastError = true)] private static extern IntPtr GetConsoleWindow(); static void Main(string[] args) { if (!IsAdmin()) { StartAsAdmin(); return; } // 操作管理员权限下的资源 } static bool IsAdmin() { var identity = System.Security.Principal.WindowsIdentity.GetCurrent(); var principal = new System.Security.Principal.WindowsPrincipal(identity); return principal.IsInRole(System.Security.Principal.WindowsBuiltInRole.Administrator); } static void StartAsAdmin() { var fileName = Process.GetCurrentProcess().MainModule.FileName; var startInfo = new ProcessStartInfo { UseShellExecute = true, WorkingDirectory = Environment.CurrentDirectory, FileName = fileName, Verb = "runas" }; Process.Start(startInfo); ShowWindow(GetConsoleWindow(), 0); } } } ``` 以上代码,IsAdmin方法用于判断当前程序是否以管理员权限运行,如果是,则执行管理员权限下的操作,否则调用StartAsAdmin方法以管理员权限重新启动程序。StartAsAdmin方法使用ProcessStartInfo对象来设置启动参数,其Verb属性设置为"runas"表示以管理员权限启动程序。注意,使用Verb属性可能会弹出UAC提示框,需要用户授权才能继续执行,如果不想显示UAC提示框,可以使用Windows API函数ShowWindow将控制台窗口隐藏。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值