How to run batch file in C # GUI form

How to execute a script package in GUI form in C #

Can someone provide a sample please?

+5
source share
3 answers

This example assumes a Windows Forms application with two text fields ( RunResultsand 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 example above is a button click event for a button with a name RunIt. There are several text fields in the form, RunResultsand Errorswhere we write the results stdoutand stderrto.

+4
source

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

, .

+5

I conclude that by executing in the form of a GUI, you mean displaying the results of execution 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
    }
}

An example taken from here .

+1
source

All Articles