Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Windows Form .Net and DOS Console

Tags:

c#

.net

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 comunicate with my windows form panel???

Thanks

like image 701
user62958 Avatar asked Dec 13 '22 03:12

user62958


2 Answers

You can call the DOS or batch program from your Form application and redirect the output to a string:

using (var p = new System.Diagnostics.Process( ))
{
    p.StartInfo.UseShellExecute = false;
    p.StartInfo.RedirectStandardOutput = true;
    p.StartInfo.FileName = PathToBatchFile;
    p.StartInfo.Arguments = args;
    p.Start( );
    string o = p.StandardOutput.ReadToEnd( );
    p.WaitForExit( );
}
like image 137
Dour High Arch Avatar answered Dec 16 '22 17:12

Dour High Arch


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<Object,DataReceivedEventArgs> 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();

}
like image 42
Cheeso Avatar answered Dec 16 '22 18:12

Cheeso