1

Why this code only shows cmd window and never reaches the end ? I want to get the output from PsList into my C# app. Execution halts on this line: "int exitCode = proc.ExitCode;"

private static void PsList()
{           
    ProcessStartInfo start = new ProcessStartInfo();            
    start.FileName = @"C:\PsList.exe";
    start.WindowStyle = ProcessWindowStyle.Hidden;
    start.CreateNoWindow = true;
    start.UseShellExecute = false;
    start.RedirectStandardOutput = true;

    using (Process proc = Process.Start(start))
    {
        proc.WaitForExit(4000);

        int exitCode = proc.ExitCode;
        string exitMsg = proc.StandardOutput.ReadToEnd();
    }
}
Qantas 94 Heavy
  • 15,750
  • 31
  • 68
  • 83
Primoz
  • 4,079
  • 17
  • 56
  • 67

2 Answers2

3

You might try rearranging things a bit:

using (Process proc = Process.Start(start))
{
    string exitMsg = proc.StandardOutput.ReadToEnd();
    proc.WaitForExit(4000);

    int exitCode = proc.ExitCode;
}

There are many related questions such as How to get log from Process.Start and ResGen.exe stucks when redirect output

Community
  • 1
  • 1
Jim Mischel
  • 131,090
  • 20
  • 188
  • 351
0

Depending on how exactly the execution halts on the proc.ExitCode line, it may be the process isn't finished by the time the ExitCode property is accessed, and then it will throw a InvalidOperationException.

In that case you could check if the process has already exited with proc.HasExited before trying to access the ExitCode property

Aether McLoud
  • 732
  • 1
  • 7
  • 20