开发者

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

开发者 https://www.devze.com 2023-03-06 11:32 出处:网络
How would you execute a batch script within开发者_如何学编程 a GUI form in C# Could anyone provide a sample please?System.Diagnotics.Process.Start(\"yourbatch.bat\"); ought to do it.

How would you execute a batch script within开发者_如何学编程 a GUI form in C#

Could anyone provide a sample please?


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

Another thread covering the same issue.


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消