当前位置: 首页 > news >正文

C#获取当前系统账户是否为管理员账户

传统方式:

WindowsPrincipal winPrincipal = new WindowsPrincipal(WindowsIdentity.GetCurrent());
bool admin = winPrincipal.IsInRole(WindowsBuiltInRole.Administrator);

这种方式虽然是最常用的检测管理员权限的方法,但是有个致命的缺陷,就是在应用程序为非管理员权限下的时候,获取的值为false,但其实当前user是管理员权限。

所以在这种情况下,需要以下面的方式获取稍为靠谱:

        static string ExecuteWithErrorHandling(string command){try{Process process = new Process{StartInfo = {FileName = "cmd.exe",Arguments = "/c " + command,RedirectStandardOutput = true,UseShellExecute = false,CreateNoWindow = true}};process.Start();string output = process.StandardOutput.ReadToEnd();process.WaitForExit();return output;}catch (Exception ex){return $"执行异常:{ex.Message}";}}static bool IsAdministratorByCurUser(){try{var identity = WindowsIdentity.GetCurrent();var executeRes = ExecuteWithErrorHandling($"net localgroup administrators | findstr \"{identity.Name}\"");return !string.IsNullOrWhiteSpace(executeRes) && executeRes.Contains(identity.Name);}catch{return false;}}

http://www.dtcms.com/a/283461.html

相关文章:

  • 资源利用率提升50%:Serverless 驱动国诚投顾打造智能投顾新范式
  • 用Amazon Q Developer助力Python快捷软件开发
  • EMS4000/EMS3900/EMS4100/EMS3157/EMS/23157高性能高质量模拟开关芯片
  • Go语言自学笔记(2.3-2.6)
  • C++:vector(2)之vector的模拟实现
  • 使用 SeaTunnel 建立从 MySQL 到 Databend 的数据同步管道
  • [2025CVPR-图象检索方向]CCIN:用于合成图像检索的合成冲突识别和中和模型
  • OWASP Top 10 攻击场景实战
  • 简单易懂,什么是连续分配管理方式
  • Vue3+Ts实现父子组件间传值的两种方式
  • 设计模式之【观察者模式】
  • 多维动态规划题解——不同路径【LeetCode】记忆化搜索
  • ai 编程工具,简单总结
  • 16路串口光纤通信FPGA项目实现指南 - 第二部分(下)
  • Day36 Java方法和流程控制练习 计算器
  • Linux运维新手的修炼手扎之第19天
  • Linux内核设计与实现 第1章:内核简介
  • UDP和TCP的主要区别是什么?
  • --- Bean 的生命周期 ---
  • Redis键过期后会立即删除吗
  • 光环效应(HALO Effect)
  • MySQL高并发高可用架构设计与实现:主从复制与读写分离
  • x86版Ubuntu的容器中运行ARM版Ubuntu
  • 3分钟实战!用DeepSeek+墨刀AI生成智能对话APP原型图
  • Karate(Java)接口自动化测试框架
  • 代码随想录算法训练营第五十天|图论part1
  • 【图像处理基石】如何入门人体关键点检测?
  • 迁移学习--基于torchvision中VGG16模型的实战
  • 【FreeRTOS#5】任务挂起与恢复实例
  • 信息收集知识总结