C#启用管理员权限运行程序
2024-08-22 14:35:17
方法一:关闭程序重新请求打开
static class Program
{
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false); /**
* 当前用户是管理员的时候,直接启动应用程序
* 如果不是管理员,则使用启动对象启动程序,以确保使用管理员身份运行
*/
//获得当前登录的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))
{
//如果是管理员,则直接运行
Application.Run(new Form1());
}
else
{
//创建启动对象
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
{
return;
}
//退出
Application.Exit();
}
}
}
方法二:修改manifest
在 项目 上 添加新项 选择“应用程序清单文件” 然后单击 添加 按钮
添加后,默认打开app.manifest文件,将:
<requestedExecutionLevel level="asInvoker" uiAccess="false" />
修改为:
<requestedExecutionLevel level="requireAdministrator" uiAccess="false" />
然后打开 项目属性 ,将 应用程序 标签页中的 资源 中的 清单 修改为新建的 app.manifest。
重新生成项目,再次打开程序时就会提示 需要以管理员权限运行。
最新文章
- Ubuntu环境下安装TinyOS系统
- java转义字符(转载)
- Wpf 数据绑定之BindingBase.StringFormat
- sqlserver提高篇
- FFMPEG结构体分析:AVPacket
- There Are Now 3 Apache Spark APIs. Here’s How to Choose the Right One
- [原创]K8_Delphi源码免杀系列教程
- JSP动态网页
- [原创] MSP430G2系列图形化编程相关资料
- cp自动创建层级结构的例子
- framework4.0 IIS7下urlrewriter设置问题
- .net core2.0 codefirst 创建数据库的问题!
- 如何安装windows7
- nginx1.9+新增tcp/udp代理stream
- 用Javascript轻松制作一套简单的抽奖系统
- SQL Server笔记——sql语句创建数据库
- 创建第一个maven项目的那些坑
- 【bzoj4898】[Apio2017]商旅 Floyd+分数规划+Spfa
- custom post types 404 Page Error
- Make 学习笔记(1)
热门文章
- Android Studio导入第三方类库的方法
- 本地数据Store。Cookie,Session,Cache的理解。Timer类主要用于定时性、周期性任务 的触发。刷新Store,Panel
- word20161222
- ovirt配置为cas登录
- nginx windows负载均衡入门
- 关于SimpleAdapter和ListView结合使用,实现列表视图的笔记
- 设计模式--适配器模式Adapter(结构型)
- 解决NetBeans运行web项目时出现的&ldquo;未能正确设置java DB&rdquo;问题
- Python3实现火车票查询工具
- Windows 网络编程