第一种方式:通过 Process.Start()
//获得当前登录的Windows用户标示
System.Security.Principal.WindowsIdentity identity = System.Security.Principal.WindowsIdentity.GetCurrent();
System.Security.Principal.WindowsPrincipal principal = new System.Security.Principal.WindowsPrincipal(identity);
//判断当前登录用户是否为管理员
if (principal.IsInRole(System.Security.Principal.WindowsBuiltInRole.Administrator))
{
//如果是管理员,则直接运行
//
//***此处添加程序启动代码**
//
}
else
{
//创建启动对象
System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
startInfo.UseShellExecute = true;
startInfo.WorkingDirectory = Environment.CurrentDirectory;
startInfo.FileName = "XXXX.exe";// Application.ExecutablePath;
//设置启动动作,确保以管理员身份运行
startInfo.Verb = "runas";
try
{
//重新已管理员身份启动;
System.Diagnostics.Process.Start(startInfo);
}
catch
{
return;
}
}
第二种方式:添加应用程序清单文件
在 项目 上 添加新项 选择“应用程序清单文件” 然后单击 添加 按钮
添加后,默认打开app.manifest文件,将:
<requestedExecutionLevel level="asInvoker" uiAccess="false" />
修改为:
<requestedExecutionLevel level="requireAdministrator" uiAccess="false" />
然后打开 项目属性 ,将 应用程序 标签页中的 资源 中的 清单 修改为新建的 app.manifest。
重新生成项目,再次打开程序时就会提示 需要以管理员权限运行。
第三种方式:修改程序文件的属性
注意:运行时可能会出现windows弹框信息确认提示,如果不想要弹框提示,可修改一下设置