.netcore 控制台程序,在window操作系统中,怎么获取管理员权限运行此程序

在.NET Core控制台程序中设置管理员权限运行需要以下步骤:

  1. 在项目的app.manifest文件中指定管理员权限:

将app.manifest文件设置为嵌入式资源

  1. 在程序中获取管理员权限:
csharp 复制代码
static void Main(string[] args) 
{ 
    var identity = WindowsIdentity.GetCurrent();
    var principal = new WindowsPrincipal(identity);
 
    if (principal.IsInRole(WindowsBuiltInRole.Administrator)) 
    {
        // 程序以管理员权限运行
    }
    else 
    {
        // 以非管理员权限运行,需要重新启动程序
        var startInfo = new ProcessStartInfo();
        startInfo.FileName = Assembly.GetExecutingAssembly().Location;
        startInfo.Verb = "runas";
        Process.Start(startInfo);
        return;
    }
 
    // 程序正常逻辑
}
  1. 运行程序,当程序以非管理员权限运行时,Windows会弹出一个用户账户控制(UAC)提示框确认是否允许程序以管理员权限运行。用户确认之后,程序即可以管理员权限运行。

注意:由于需要在app.manifest中指定管理员权限,因此程序需要重新生成和发布。在程序运行时无法动态获取管理员权限。

相关推荐
宝桥南山12 小时前
.NET 11 - 尝试一下Minimal API中的异步验证新特性
microsoft·微软·c#·asp.net·.net·.netcore
上位机妹子5 天前
EF Core 两种继承映射:每层次一张表(TPH)与每类型一张表(TPT)
数据库·c#·.netcore·ef core
csdn_aspnet1 个月前
.NetCore Webapi 接口验证请求来源
.netcore·ip·token·签名·webapi·cors·sign
宝桥南山1 个月前
Microsoft Fabric - 简单尝试一下Microsoft Fabric .NET SDK
microsoft·微软·.net·.netcore·powerbi·fabric
geovindu1 个月前
CSharp:Condition Variable Pattern
后端·设计模式·c#·.net·.netcore·条件变量模式·同步型模式
geovindu1 个月前
CSharp: Observer Pattern
开发语言·后端·观察者模式·设计模式·c#·.netcore·行为模式
geovindu1 个月前
CSharp: Strategy Pattern
开发语言·后端·c#·.net·.netcore·策略模式·行为模式
geovindu1 个月前
CSharp: Task Scheduler
开发语言·后端·c#·.net·.netcore
geovindu1 个月前
CSharp: Wordcloud
开发语言·后端·c#·.net·.netcore·词云
geovindu1 个月前
CSharp: Command Pattern
开发语言·后端·c#·.net·.netcore·命令模式·行为模式