c# - C# 程序如何以管理员权限运行另一个程序?

标签 c# windows process privileges

我对这种情况有疑问: 我做了2个程序:

第一个只是打印一个输出,说明是否使用管理员权限启动,第二个,使用管理员权限执行第一个程序并且不使用UAC。问题是第二个程序无法使用管理员权限启动第一个程序,我不知道为什么。 这是我的代码:

第一个程序的代码:

// This only prints if you start as administrator or not.
bool isElevated;
WindowsIdentity identity = WindowsIdentity.GetCurrent();
WindowsPrincipal principal = new WindowsPrincipal(identity);
isElevated = principal.IsInRole(WindowsBuiltInRole.Administrator);
Console.WriteLine("I got admin privileges?: "+isElevated);

第二个程序的代码:

// This execute the first program with admin privileges without UAC
string username = "myuser";
SecureString userpass = new SecureString();
userpass.AppendChar('m');
userpass.AppendChar('y');
userpass.AppendChar('p');
userpass.AppendChar('a');
userpass.AppendChar('s');
userpass.AppendChar('s');

Process program = new Process();
program.StartInfo.UserName = username;
program.StartInfo.Password = userpass;
program.StartInfo.FileName = "Path/First_program.exe";
program.StartInfo.UseShellExecute = false;
program.Start();

PD:我不希望用户打开 UAC,这就是我已经插入用户名和密码的原因。 提前致谢。

最佳答案

你已经回答了一半了。另一半是程序必须请求以提升的权限执行。默认情况下,Windows 程序以“基本”信任级别运行,无论用户可能拥有的真实权限级别如何。要获得管理权限,该程序必须请求提升,根据定义,这将涉及 UAC。

像您这样的程序可以使用 ProcessStartInfo 中的 runas 动词来请求提升,或者通过在任一应用程序的 list 中指定 requireAdministrator 提升的权限(假设您控制它们)。无论哪种方式,如果启用了 UAC,用户都会收到提示。

避免此问题的唯一方法是将需要提升权限的程序设置为 Windows 服务,并在 services.msc 中配置为使用管理权限运行。当安装/注册以这种方式运行的服务时,您将收到一个 UAC 提示,从那时起,该服务可以执行该任务,而无需任何进一步的 UAC 操作。然后,您可以使用各种通信技术(从命名管道到 TCP 等真正的网络通信)来向服务发出信号,表明它应该执行您想要的操作。

关于c# - C# 程序如何以管理员权限运行另一个程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42796242/

相关文章:

windows - docker:是否可以从另一个容器中启动 native Windows 同级容器?

multithreading - 当Apache工作程序启动其自己的工作程序线程或进程时会发生什么?

c# - 使用 Automapper 将集合的属性映射到基元数组

c# - ExpressionTree Compile() 方法生成 stackoverflow 异常

windows - 使用 QProcess 获取所有正在运行的进程信息

python - 无法在 Windows 上通过 Python 生成 azure TTS

c - 我如何在这个简单的 C shell 中设置超时?

.net - 分析进程中加载​​的 native DLL 和程序集的内存占用的工具?

c# - WinForms 执行调用异步方法而不阻塞 UI 的同步方法

c# - Azure:表脚本不是由 sql 执行触发的