C#学习四之输入输出重定向

在窗体程序的创建中,可以给一个button添加一个事件让它去调用其它程序,并将其他程序的输出返回到窗口上,避免了控制台应用难看的界面,以下是实例:

// Start the child process.

Process p = new Process();

// Redirect the output stream of the child process.

p.StartInfo.UseShellExecute = false;

p.StartInfo.RedirectStandardOutput = true;

p.StartInfo.RedirectStandardInput = true;

p.StartInfo.RedirectStandardError = true;

p.StartInfo.CreateNoWindow = true;

p.StartInfo.FileName = @"calCRC.exe"; //别忘了把exe放到窗口程序的bin的debug目录下,这是相对路径

p.Start();

// Do not wait for the child process to exit before

// reading to the end of its redirected stream.

// p.WaitForExit();

// Read the output stream first and then wait.

p.StandardInput.WriteLine(textBox1.Text);     //重定向标准输入,将会作为calCRC的输入

string output = p.StandardOutput.ReadToEnd();  //重定向标准输出,将会把calCRC的输出存下来 

string error = p.StandardError.ReadToEnd();    //重定向标准错误

if(output != null)

textBox2.Text = output;

else

{

textBox2.Text = error;

}