• 启动管理员进程


    启动管理员进程

    当我们运行一个程序的时候有时需要提升到管理员权限,但是默认的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();
                }
            }
        }
    }
    
    
  • 相关阅读:
    JavaWeb
    List的三种遍历(转)
    Java中父类和子类集合互相转换(转)
    Day4
    Ubuntu20.04配置 ES7.17.0集群
    K8S中部署apisix(非ingress)
    使用 Flutter&&Hive&&Bloc 写一个待办小demo
    SQL多行数据分组后合并某个字段
    sql group 拼接字段
    Socket
  • 原文地址:https://www.cnblogs.com/guodf/p/6656906.html
Copyright © 2020-2023  润新知