C# Windows Form .Net and DOS Console

前端 未结 6 783
走了就别回头了
走了就别回头了 2020-12-04 02:50

I have a windows form that executes a batch file. I want to transfer everything that happends in my console to a panel in my form. How can I do this? How can my DOS console

6条回答
  •  失恋的感觉
    2020-12-04 03:08

    The doc states that if you want to read both StandardError and StandardOutput, you need to read at least one of them asynchronously in order to avoid deadlocks.

    Also, if you call ReadToEnd on one of the redirected streams, you must do so before calling WaitForExit(). If you WaitForExit before ReadToEnd, the output buffer can fill up, suspending the process, which means it will never exit. That would be a very long wait. This is also in the doc!

    example:

    string output;
    string error;
    System.Diagnostics.Process p = new System.Diagnostics.Process
        {
            StartInfo =
            {
                FileName = program,
                Arguments = args,
                WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden,
                UseShellExecute = false,
            }
        };
    
    if (waitForExit)
    {
        StringBuilder sb = new StringBuilder();
        p.StartInfo.RedirectStandardOutput = true;
        p.StartInfo.RedirectStandardError = true;
        Action stdErrorRead = (o,e) =>
        {
            if (!String.IsNullOrEmpty(e.Data))
                sb.Append(e.Data);
        };
    
        p.ErrorDataReceived += stdErrorRead;
        p.Start();
        // begin reading stderr asynchronously
        p.BeginErrorReadLine();
        // read stdout synchronously
        output = p.StandardOutput.ReadToEnd();
        p.WaitForExit();
        // return code is in p.ExitCode
    
        if (sb.Length > 0)
            error= sb.ToString();
    
    }
    

提交回复
热议问题