项目中打包程序,在后续更新时需要管理员身份运行,固将程序运行时,使用管理员运行。
作如下设置
1)在App.cs中增加以下代码:
/// <summary> /// 检查是否是管理员身份 /// </summary> private void CheckAdministrator() { var wi = WindowsIdentity.GetCurrent(); var wp = new WindowsPrincipal(wi); bool runAsAdmin = wp.IsInRole(WindowsBuiltInRole.Administrator); if (!runAsAdmin) { // It is not possible to launch a ClickOnce app as administrator directly, // so instead we launch the app as administrator in a new process. var processInfo = new ProcessStartInfo(Assembly.GetExecutingAssembly().CodeBase); // The following properties run the new process as administrator processInfo.UseShellExecute = true; processInfo.Verb = "runas"; // Start the new process try { Process.Start(processInfo); } catch (Exception ex) { ex.WriteLog(); } // Shut down the current process Environment.Exit(0); } }
2)重写 OnStartup 函数
protected override void OnStartup(StartupEventArgs e) { base.OnStartup(e); CheckAdministrator();
//如果不是管理员,程序会直接退出。
StartupUri = new Uri("MainWindow.xaml", UriKind.RelativeOrAbsolute); }