Search code examples
c#exeexternal-application

Proper way to run PsList.exe from my C# app and get its output (Or why my code doesn't work)?


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();
    }
}

Solution

  • 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