在C#中的GUI表单中你将如何执行批处理脚本
How would you execute a batch script within a GUI form in C#
谁能提供样本吗?
本示例假定Windows窗体应用程序有两个文本框(RunResults 和错误
)。
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;
}
}
}
更新:
样品上面的一个按钮单击事件的一个名为按钮 RunIt
。有形式的一对夫妇的文本框, RunResults
和错误
在这里我们写的结果标准输出
和标准错误
到
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.