在未提升的上下文中执行代码

Execute Code in an Unelevated Context

我的应用程序 运行宁作为管理员(提升),但我需要 运行 当前用户上下文中的某些代码块(未提升)。

  1. 如何在未提升的上下文中 运行 给定的代码块?

    有没有一种不需要我知道用户的域、名称和密码的模拟方法?

    是否有另一个 API 可以做到这一点,或者可以简单地使用属性来实现?

  2. 同样,有没有办法检测到我目前 运行处于提升的环境中,以便我知道我需要首先降低提升?

我正在使用 C# 6.0、.NET 4.x(其中 x >= 5)和 Visual Studio 2015。

  1. 您可以通过将需要 运行 取消提升的代码封装在单独的程序集(.exe 文件)中并将其作为新进程启动来实现。看看Start non-elevated process from elevated process.
  2. 检查您是否处于提升的上下文中:

    static bool IsAdministrator()
    {
        WindowsIdentity identity = WindowsIdentity.GetCurrent();
        WindowsPrincipal principal = new WindowsPrincipal(identity);
        return principal.IsInRole (WindowsBuiltInRole.Administrator);
    }
    

    (摘自:Detect if running as Administrator with or without elevated privileges?