Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run a batch file within a C# GUI form

Tags:

c#

.net

windows

How would you execute a batch script within a GUI form in C#

Could anyone provide a sample please?

like image 358
Mike Avatar asked May 14 '11 22:05

Mike


3 Answers

System.Diagnotics.Process.Start("yourbatch.bat"); ought to do it.

Another thread covering the same issue.

like image 147
Will A Avatar answered Oct 23 '22 00:10

Will A


This example assumes a Windows Forms application with two text boxes (RunResults and Errors).

// Remember to also add a using System.Diagnostics at the top of the class
private void RunIt_Click(object sender, EventArgs e)
{
    using (Process p = new Process())
    {
        p.StartInfo.WorkingDirectory = "<path to batch file folder>";
        p.StartInfo.FileName = "<path to batch file itself>";
        p.StartInfo.UseShellExecute = false;
        p.StartInfo.RedirectStandardOutput = true;
        p.StartInfo.RedirectStandardError = true;
        p.Start();
        p.WaitForExit();

        // Capture output from batch file written to stdout and put in the 
        // RunResults textbox
        string output = p.StandardOutput.ReadToEnd();
        if (!String.IsNullOrEmpty(output) && output.Trim() != "")
        {
            this.RunResults.Text = output;
        }

        // Capture any errors written to stderr and put in the errors textbox.
        string errors = p.StandardError.ReadToEnd();
        if (!String.IsNullOrEmpty(errors) & errors.Trim() != ""))
        {
            this.Errors.Text = errors;
        }
    }
}

Updated:

The sample above is a button click event for a button called RunIt. There's a couple of text boxes on the form, RunResults and Errors where we write the results of stdout and stderr to.

like image 35
Kev Avatar answered Oct 22 '22 23:10

Kev


I deduce that by executing within a GUI form you mean showing execution results within some UI-Control.

Maybe something like this:

private void runSyncAndGetResults_Click(object sender, System.EventArgs e)     
{
    System.Diagnostics.ProcessStartInfo psi =
       new System.Diagnostics.ProcessStartInfo(@"C:\batch.bat");

    psi.RedirectStandardOutput = true;
    psi.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
    psi.UseShellExecute = false;

    System.Diagnostics.Process batchProcess;
    batchProcess = System.Diagnostics.Process.Start(psi);

    System.IO.StreamReader myOutput = batchProcess.StandardOutput;
    batchProcess.WaitForExit(2000);
    if (batchProcess.HasExited)
    {
        string output = myOutput.ReadToEnd();

        // Print 'output' string to UI-control
    }
}

Example taken from here.

like image 33
Joao Avatar answered Oct 22 '22 22:10

Joao