首页 > 系统服务 > 详细

启动管理员进程

时间:2019-11-07 15:16:31      阅读:79      评论:0      收藏:0      [点我收藏+]

启动管理员进程

当我们运行一个程序的时候有时需要提升到管理员权限,但是默认的C#程序的运行权限是当前用户的权限,那么怎么提升这个启动权限呢?

经过网上的一番搜索后,找到如下两种方式:

1. 通过应用程序清单文件实现(app.mainfest)

创建app.mainfest的两种办法:

  1. 第一种办法:

在项目的【Properties】上添加【新建项】,弹出窗口找到【应用程序清单文件】,最后【确定】。
技术分享图片

  1. 第二种办法:

查看项目的【属性】,在属性页找到【安全性】,然后点击【启用ClickOnce安全设置】,然后保存(ctrl+s),你会发现Preperties目录下生成了app.mainfest文件,然后再取消【启用ClickOnce安全设置】的选中状态。
技术分享图片

创建app.mainfest文件后,打开并编辑做以下修改:
asInvoker改为requireAdministrator
技术分享图片

2. 通过添加代码来实现

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Security.Principal;
using System.Windows.Forms;

namespace Test
{
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            WindowsIdentity identity = WindowsIdentity.GetCurrent();
            WindowsPrincipal principal = new WindowsPrincipal(identity);
            //判断当前用户是否为管理员
            if (principal.IsInRole(WindowsBuiltInRole.Administrator))
            {
                //如果是管理员,则直接运行
                Application.Run(new Form1());
            }
            else
            {
                //创建启动对象
                ProcessStartInfo startInfo = new ProcessStartInfo();
                startInfo.UseShellExecute = true;
                startInfo.WorkingDirectory = Environment.CurrentDirectory;
                startInfo.FileName = Application.ExecutablePath;
                //设置启动动作,确保以管理员身份运行
                startInfo.Verb = "runas";
                Process.Start(startInfo);
                //退出               
                Application.Exit();
            }
        }
    }
}

启动管理员进程

原文:https://www.cnblogs.com/guodf/p/6656906.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!