我的博客
个人资料:
AlanThinker
AlanThinker@stk.me

C#程序在运行后请求管理员权限来执行某项操作

软件开发 发表时间:2016-11-10 更新时间:2017-05-26

有一个变通的做法.
* 在程序中用管理员权限重新打开自己.
* 在main函数中判断传入的参数, 执行完需要权限的功能后, 直接return.
//Request administrator rule to do it.
var psi = new ProcessStartInfo();
psi.FileName = Assembly.GetExecutingAssembly().Location;
psi.Arguments = "ClearEventLog " + menuItem.Text;
psi.Verb = "runas";

var process = new Process();
process.StartInfo = psi;
process.Start();
process.WaitForExit(); 
                                    
static void Main(string[] args)
{
    if (args.Length > 0)
    {
        if (args[0].ToLower() == "ClearEventLog".ToLower())
        {
            MainForm.ClearEventLog(args[1]);
            return;
        }
    }
    
    ......
}    

或者:
 
        static void StartMyselfAsAdmin()
        {
            //Request administrator rule to do it.
            var psi = new ProcessStartInfo();
            psi.FileName = Assembly.GetExecutingAssembly().Location;
            psi.Arguments = string.Join(" ", Environment.GetCommandLineArgs().Skip(1).ToArray());
            psi.Verb = "runas";

            var process = new Process();
            process.StartInfo = psi;
            process.Start();
            process.WaitForExit();
        }

        public static bool IsAdministrator()
        {
            WindowsIdentity current = WindowsIdentity.GetCurrent();
            WindowsPrincipal windowsPrincipal = new WindowsPrincipal(current);
            return windowsPrincipal.IsInRole(WindowsBuiltInRole.Administrator);
        }

        static void Main(string[] args)
        {
            if(!IsAdministrator())
                StartMyselfAsAdmin();
        }

 
IP Address: 43.129.217.254