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

相关推荐
刘梦凡呀1 天前
C# .NET Core 批量下载文件
windows·c#·.netcore
Zhen (Evan) Wang2 天前
.NET 6 WPF 利用CefSharp.Wpf.NETCore显示PDF文件
.net·wpf·.netcore
时光追逐者2 天前
C#/.NET/.NET Core拾遗补漏合集(25年4月更新)
c#·.net·.netcore
追雨潮2 天前
.net core 项目快速接入Coze智能体-开箱即用-第2节
.netcore
追雨潮3 天前
.net core 项目快速接入Coze智能体-开箱即用-全局说明
.netcore·ai编程
时光追逐者3 天前
C#/.NET/.NET Core技术前沿周刊 | 第 35 期(2025年4.14-4.20)
c#·.net·.netcore
全栈小54 天前
【C#】.net core 6.0调用MVC API接口时,提示Unsupported Media Type,状态码415
c#·mvc·.netcore
猫霸4 天前
理解.NET Core中的配置Configuration
html·.netcore·xhtml
MoFe14 天前
【.net core】【watercloud】数据库连接报错问题
数据库·.netcore
csdn_aspnet4 天前
Windows .NET Core 应用程序部署到 IIS 解决首次访问加载慢的问题
iis·.netcore