I am trying to run logman.exe
for a elevated CMD
, for this below code I tried,
var proc = new Process
{
StartInfo = new ProcessStartInfo
{
FileName = @"C:\Windows\System32\cmd.exe",
Arguments = "cmd /k logman.exe PerfCounterCustom | findstr \"Root\"",
Verb = "runas",
UseShellExecute = true,
}
};
try
{
proc.Start();
while (!proc.StandardOutput.EndOfStream)
{
string line = proc.StandardOutput.ReadLine();
}
Console.WriteLine("Successfully elevated!");
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
And it's giving error output like,
System.InvalidOperationException: StandardOut has not been redirected or the process hasn't started yet.
at System.Diagnostics.Process.get_StandardOutput()
2 Questions,
- when I am running application
exe
, it's showing 2CMD
window, the 1st one showing error and 2nd one showing result for argument"cmd /k logman.exe PerfCounterCustom | findstr \"Root\""
[Root Path]
how to disable showing both window?
- Why I am getting this error?
You have to set
RedirectStandardOutput
of theProcessStartInfo
totrue
and you have to runproc.WaitForExit()
before reading the output. Please note that this solution causes incompatibilities with running the process as administrator via runas.An alternative solution to read the output of the command is to write the output to a text file. Therefore you have to add
>> "[Name or Path of file].txt"
to the end of your command. Then just read the file from C# e.g. withFile.ReadAllLines
. Two things to consider here: If you do that often at Runtime and the command delivers huge amounts of text don't write it to an SSD. Please check that the file is empty / not existing before, because Windows just appends the output to the end of the file. If you run that in multiple threads use a thread identifier in the file name.To your 1st Question: In the
ProcessStartInfo
setWindowStyle
toProcessWindowStyle.Hidden