C#判断程序是否以管理员运行

2021-04-06 12:26

阅读:352

标签:exec   try   ali   scheduler   以管理员身份运行   psi   proc   tin   运行   

    ///


         /// 判断程序是否是以管理员身份运行。
         ///

         public static bool IsRunAsAdmin()
         {
             WindowsIdentity id = WindowsIdentity.GetCurrent();
             WindowsPrincipal principal = new WindowsPrincipal(id);
             return principal.IsInRole(WindowsBuiltInRole.Administrator);
         }

   //不是以管理员身份开启,则自动以管理员身份重新打开程序
   //写在构造里比较省资源
   public LoginFrm()
         {
             try
             {
                 //判断是否以管理员身份运行,不是则提示
                 if (!PublicUtil.IsRunAsAdmin())
                 {
                     ProcessStartInfo psi = new ProcessStartInfo();
                     psi.WorkingDirectory = Environment.CurrentDirectory;
                     psi.FileName = Application.ExecutablePath;
                     psi.UseShellExecute = true;
                     psi.Verb = "runas";
                     Process p = new Process();
                     p.StartInfo = psi;
                     p.Start();
                     Process.GetCurrentProcess().Kill();
                 }
             }
             catch (Exception ex)
             {
                 ExceptionScheduler.ExceptionScheduler exceptionScheduler = new ExceptionScheduler.ExceptionScheduler(ex);
                 ShowMessageOnUI.ShowErrorMessage("程序无法获取Windows管理员身份运行,\n请手动使用Windows管理员身份运行");
             }
             InitializeComponent();
         }

C#判断程序是否以管理员运行

标签:exec   try   ali   scheduler   以管理员身份运行   psi   proc   tin   运行   

原文地址:https://www.cnblogs.com/hrkblogs/p/9133154.html


评论


亲,登录后才可以留言!