Keep console window of a new Process open after it finishes

前端 未结 4 1785
一向
一向 2020-12-01 10:15

I currently have a portion of code that creates a new Process and executes it from the shell.

Process p = new Process();
...
p.Start();
p.WaitForExit();


        
相关标签:
4条回答
  • 2020-12-01 10:51

    It is easier to just capture the output from both the StandardOutput and the StandardError, store each output in a StringBuilder and use that result when the process is finished.

    var sb = new StringBuilder();
    
    Process p = new Process();
    
    // redirect the output
    p.StartInfo.RedirectStandardOutput = true;
    p.StartInfo.RedirectStandardError = true;
    
    // hookup the eventhandlers to capture the data that is received
    p.OutputDataReceived += (sender, args) => sb.AppendLine(args.Data);
    p.ErrorDataReceived += (sender, args) => sb.AppendLine(args.Data);
    
    // direct start
    p.StartInfo.UseShellExecute=false;
    
    p.Start();
    // start our event pumps
    p.BeginOutputReadLine();
    p.BeginErrorReadLine();
    
    // until we are done
    p.WaitForExit();
    
    // do whatever you need with the content of sb.ToString();
    

    You can add extra formatting in the sb.AppendLine statement to distinguish between standard and error output, like so: sb.AppendLine("ERR: {0}", args.Data);

    0 讨论(0)
  • 2020-12-01 11:06

    Regarding: "Member Process.Start(ProcessStartInfo) cannot be accessed with an instance reference; qualify it with a type name instead"

    This fixed the problem for me....

    ProcessStartInfo psi = new ProcessStartInfo();
    psi.FileName = "CMD.EXE";
    psi.Arguments = "/K yourmainprocess.exe";
    Process p = Process.Start(psi);
    p.WaitForExit();
    
    0 讨论(0)
  • 2020-12-01 11:06

    Be carefull espacially on switch /k, because in many examples is usually used /c.

    CMD /K Run Command and then return to the CMD prompt.

    CMD /C Run Command and then terminate

    var p = new Process();
    p.StartInfo.FileName = "cmd.exe";
    p.StartInfo.Arguments = "/k yourmainprocess.exe";
    p.Start();
    p.WaitForExit();
    
    0 讨论(0)
  • 2020-12-01 11:11

    This will open the shell, start your executable and keep the shell window open when the process ends

    Process p = new Process();
    ProcessStartInfo psi = new ProcessStartInfo();
    psi.FileName = "CMD.EXE";
    psi.Arguments = "/K yourmainprocess.exe";
    p.StartInfo = psi;
    p.Start();
    p.WaitForExit();
    

    or simply

    ProcessStartInfo psi = new ProcessStartInfo();
    psi.FileName = "CMD.EXE";
    psi.Arguments = "/K yourmainprocess.exe";
    Process p = Process.Start(psi);
    if(p != null && !p.HasExited)
        p.WaitForExit();
    
    0 讨论(0)
提交回复
热议问题