需求场景:
有的时候我们写的exe程序希望用户是以管理员身份运行的,否则会有权限问题,那么如何设置exe程序必须以管理员身份运行呢?
解决办法:将下面region中的代码添加到Program.cs中即可
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApp4
{
static class Program
{
/// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main()
{
#region 必须以管理员身份启动
//获得当前登录的Windows用户标示
if (!new System.Security.Principal.WindowsPrincipal(System.Security.Principal.WindowsIdentity.GetCurrent()).IsInRole(System.Security.Principal.WindowsBuiltInRole.Administrator))
{
//创建启动对象
System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
//设置运行文件
startInfo.FileName = System.Windows.Forms.Application.ExecutablePath;
//设置启动动作,确保以管理员身份运行
startInfo.Verb = "runas";
try
{
//如果不是管理员,则启动UAC
System.Diagnostics.Process.Start(startInfo);
}
catch { }
//退出
System.Windows.Forms.Application.Exit();
return;
}
#endregion
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
}
这样再以普通用户运行的话就会自动弹出提示了(如果你设置UAC级别最低的话不会弹框,将会自动以管理员身份重新启动运行):
另附:设置UAC级别的方法:
win+r 输入msconfig