dotnet 判断程序当前使用管理员运行降低权使用普通权限运行

栏目: ASP.NET · 发布时间: 5年前

内容简介:有一些程序是不想通过管理员权限运行的,因为在很多文件的读写,如果用了管理员权限程序写入的程序,其他普通权限的程序是无法直接访问的。 本文告诉大家如何判断当前的程序是通过管理员权限运行,然后通过资源管理器使用普通权限运行通过下面代码可以判断当前的程序是管理员权限运行如果是 dotnet core 程序,需要安装

有一些程序是不想通过管理员权限运行的,因为在很多文件的读写,如果用了管理员权限程序写入的程序,其他普通权限的程序是无法直接访问的。 本文告诉大家如何判断当前的程序是通过管理员权限运行,然后通过资源管理器使用普通权限运行

通过下面代码可以判断当前的程序是管理员权限运行

var identity = WindowsIdentity.GetCurrent();
            var principal = new WindowsPrincipal(identity);
            if (principal.IsInRole(WindowsBuiltInRole.Administrator))
            {
                // 当前正在以管理员权限运行。
            }

如果是 dotnet core 程序,需要安装 Microsoft.Windows.Compatibility 才可以使用上面代码

通过 Explorer 运行自己,在 dotnet framework 程序和 dotnet core 程序在获得自己的 exe 文件的方法是不同的

在 dotnet framework 程序可以直接在 Main 函数通过 Assembly.GetEntryAssembly().Location 拿到 exe 文件的路径

Process.Start("explorer.exe", Assembly.GetEntryAssembly().Location);

但是如果在 dotnet core 程序,通过 Assembly.GetEntryAssembly().Location 会拿到 xx.dll 而不是 exe 的路径,需要使用下面的代码拿到 exe 的文件

// 方法1

                var file = new FileInfo(Assembly.GetExecutingAssembly().Location);
                var exe = Path.Combine(file.DirectoryName, file.Name.Replace(file.Extension, "")+".exe");

// 方法2
                var exe = Process.GetCurrentProcess().MainModule.FileName;

// 更多方法

然后自己关闭

var identity = WindowsIdentity.GetCurrent();
            var principal = new WindowsPrincipal(identity);
            if (principal.IsInRole(WindowsBuiltInRole.Administrator))
            {
                var file = new FileInfo(Assembly.GetExecutingAssembly().Location);
                var exe = Path.Combine(file.DirectoryName, file.Name.Replace(file.Extension, "") + ".exe");
           	
                // 检测到当前进程是以管理员权限运行的,于是降权启动自己之后,把自己关掉。
                Process.Start("explorer.exe", Assembly.GetEntryAssembly().Location);
                Environment.Exit(0);
            }

在 Windows 系统上降低 UAC 权限运行程序(从管理员权限降权到普通用户权限) - walterlv


以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

The Probabilistic Method

The Probabilistic Method

Noga Alon、Joel H. Spencer / Wiley-Interscience / 2008-8-11 / USD 137.00

Praise for the Second Edition : "Serious researchers in combinatorics or algorithm design will wish to read the book in its entirety...the book may also be enjoyed on a lighter level since the diffe......一起来看看 《The Probabilistic Method》 这本书的介绍吧!

HTML 压缩/解压工具
HTML 压缩/解压工具

在线压缩/解压 HTML 代码

JSON 在线解析
JSON 在线解析

在线 JSON 格式化工具

正则表达式在线测试
正则表达式在线测试

正则表达式在线测试