在无法升级的上下文中执行代码

时间:2016-05-10 22:44:18

标签: c# .net .net-4.5 impersonation

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

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

    有没有办法通过假冒来做到这一点,并不要求我知道用户的域名,姓名和密码?

    是否有其他API,或者只是使用属性来实现?

  2. 同样,有没有办法检测我目前是否在高架环境中运行,以便我知道我需要首先降级?

  3. 我使用的是C#6.0,.NET 4.x(其中x> = 5)和Visual Studio 2015。

1 个答案:

答案 0 :(得分:0)

  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?

相关问题