aba*_*hev 18 c# uac processstartinfo elevated-privileges
我想启动一个具有提升权限但具有隐藏窗口的子进程(实际上是相同的控制台应用程序).
我做下一个:
var info = new ProcessStartInfo(Assembly.GetEntryAssembly().Location)
{
UseShellExecute = true, // !
Verb = "runas",
};
var process = new Process
{
StartInfo = info
};
process.Start();
Run Code Online (Sandbox Code Playgroud)
这工作:
var identity = new WindowsPrincipal(WindowsIdentity.GetCurrent());
identity.IsInRole(WindowsBuiltInRole.Administrator); // returns true
Run Code Online (Sandbox Code Playgroud)
但是UseShellExecute = true
创建了一个新窗口,我也无法重定向输出.
所以我下次做的时候:
var info = new ProcessStartInfo(Assembly.GetEntryAssembly().Location)
{
RedirectStandardError = true,
RedirectStandardOutput = true,
UseShellExecute = false, // !
Verb = "runas"
};
var process = new Process
{
EnableRaisingEvents = true,
StartInfo = info
};
DataReceivedEventHandler actionWrite = (sender, e) =>
{
Console.WriteLine(e.Data);
};
process.ErrorDataReceived += actionWrite;
process.OutputDataReceived += actionWrite;
process.Start();
process.BeginOutputReadLine();
process.BeginErrorReadLine();
process.WaitForExit();
Run Code Online (Sandbox Code Playgroud)
这不会提升权限,上面的代码返回false.为什么??
在我的情况下,一旦提升的子进程完成就可以获得输出.这是我提出的解决方案.它使用临时文件:
var output = Path.GetTempFileName();
var process = Process.Start(new ProcessStartInfo
{
FileName = "cmd",
Arguments = "/c echo I'm an admin > " + output, // redirect to temp file
Verb = "runas", // UAC prompt
UseShellExecute = true,
});
process.WaitForExit();
string res = File.ReadAllText(output);
// do something with the output
File.Delete(output);
Run Code Online (Sandbox Code Playgroud)