管理员身份运行程序
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); } } }
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步