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

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

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

    <requestedExecutionLevel level="requireAdministrator" />

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中指定管理员权限,因此程序需要重新生成和发布。在程序运行时无法动态获取管理员权限。

相关推荐
weixin_379880926 天前
.Net Core WebApi集成Swagger
java·服务器·.netcore
The Future is mine8 天前
.Net Core 在Linux系统下创建服务
linux·运维·.netcore
*长铗归来*9 天前
ASP.NET Core Web API 中控制器操作的返回类型及Swagger
后端·c#·asp.net·.netcore
IDOlaoluo9 天前
VS2017 安装 .NET Core 2.2 SDK 教程(包括 dotnet-sdk-2.2.108-win-x64.exe 安装步骤)
.netcore
csdn_aspnet17 天前
使用 Entity Framework Code First 方法创建 ASP.NET Core 5.0 Web API
.netcore·webapi
小先生81217 天前
.NET Core项目中 Serilog日志文件配置
c#·.netcore
爱吃香蕉的阿豪17 天前
.NET Core 中 System.Text.Json 与 Newtonsoft.Json 深度对比:用法、性能与场景选型
数据库·json·.netcore
csdn_aspnet17 天前
ASP.NET Core 10.0 的主要变化
.netcore
csdn_aspnet20 天前
在 C# .NETCore 中使用 MongoDB(第 1 部分):驱动程序基础知识和插入文档
mongodb·.netcore
csdn_aspnet20 天前
在 C# .NETCore 中使用 MongoDB(第 3 部分):跳过、排序、限制和投影
mongodb·c#·.netcore