管理员身份运行程序

时间:2022-03-17 14:42:50

 

 

管理员身份运行程序管理员身份运行程序
    public class WindowsIdentityHelper
    {
        private static ILog _logger = LogManager.GetLogger("WindowsIdentityHelper");
        /// <summary>
        /// 是否赋予管理员权限
        /// </summary>
        /// <returns></returns>
        public bool IsAdministrator()
        {
            WindowsIdentity identity = WindowsIdentity.GetCurrent();
            WindowsPrincipal principal = new WindowsPrincipal(identity);
            return principal.IsInRole(WindowsBuiltInRole.Administrator);
        }

        /// <summary>
        /// /// <summary>
        /// 以管理员权限运行程序
        /// </summary>
        /// </summary>
        /// <param name="localurl">可执行程序路径</param>
        public void RunAsAdministrator(string localurl,bool isRunAs = true)
        {
            try
            {
                //创建启动对象
                System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
                startInfo.FileName = localurl;
                if (isRunAs)
                {
                    startInfo.Verb = "runas"; //设置启动动作,确保以管理员身份运行
                }
                startInfo.WorkingDirectory = new FileInfo(localurl).DirectoryName;
                startInfo.CreateNoWindow = false;
                startInfo.UseShellExecute = false;
                startInfo.RedirectStandardOutput = true;
                startInfo.Arguments = "1";
             
                System.Diagnostics.Process.Start(startInfo);
             
            }
            catch(Exception ex)
            {
                _logger.Error("以管理员权限运行程序:" + ex.Message);
            }
        }

        /// <summary>
        /// 自动以管理员权限运行
        /// </summary>
        /// <param name="isRunAs"></param>
        public void RunSelfAsAdministrator(bool isRunAs = true)
        {
            //创建启动对象
            System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
            startInfo.UseShellExecute = true;
            startInfo.WorkingDirectory = Environment.CurrentDirectory;
            startInfo.FileName = Application.ExecutablePath;
            //设置启动动作,确保以管理员身份运行
            startInfo.Verb = "runas";
            try
            {
                System.Diagnostics.Process.Start(startInfo);
            }
            catch (Exception ex)
            {
                _logger.Error("自动以管理员权限运行:" + ex.Message);
            }
        }
    }
View Code