如何在C#GUI表单中运行批处理文件

时间:2011-05-14 22:07:15

标签: c# .net windows

如何在C#

中的GUI表单中执行批处理脚本

有人可以提供样品吗?

3 个答案:

答案 0 :(得分:5)

System.Diagnotics.Process.Start( “yourbatch.bat”);应该这样做。

Another thread covering the same issue

答案 1 :(得分:4)

此示例假定Windows窗体应用程序包含两个文本框(RunResultsErrors)。

// 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;
        }
    }
}

<强>更新

上面的示例是名为RunIt的按钮的按钮单击事件。表单上有几个文本框RunResultsErrors,我们将stdoutstderr的结果写入。

答案 2 :(得分:1)

我推断,通过在GUI表单中执行,你的意思是在一些UI-Control中显示执行结果。

也许是这样的:

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
    }
}

取自here

的示例