内容简介:有一些程序是不想通过管理员权限运行的,因为在很多文件的读写,如果用了管理员权限程序写入的程序,其他普通权限的程序是无法直接访问的。 本文告诉大家如何判断当前的程序是通过管理员权限运行,然后通过资源管理器使用普通权限运行通过下面代码可以判断当前的程序是管理员权限运行如果是 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);
}
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网
猜你喜欢:- 使用 Maven 运行单元测试
- 使用swoole运行thrift服务
- 使用Docker运行整套项目组件
- 使用jconsole监控JVM运行状况
- Goland使用初探以及运行流程浅析
- 使用Elm实现生产系统运行零异常
本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
The Everything Store
Brad Stone / Little, Brown and Company / 2013-10-22 / USD 28.00
The definitive story of Amazon.com, one of the most successful companies in the world, and of its driven, brilliant founder, Jeff Bezos. Amazon.com started off delivering books through the mail. Bu......一起来看看 《The Everything Store》 这本书的介绍吧!