還有一個辦法將所有輸出作爲事件獲取,並在其他控制檯應用程序輸出cmd_DataReceived
時獲得所有輸出,並且每當有輸出時都會引發輸出,並且在其他應用程序中引發錯誤時引發cmd_Error
。
如果你想解析輸出,可能處理這些事件是更好的方式來讀取輸出並處理其他應用程序出現錯誤的時候。
using System;
using System.Diagnostics;
namespace InteractWithConsoleApp
{
class Program
{
static void Main(string[] args)
{
ProcessStartInfo cmdStartInfo = new ProcessStartInfo();
cmdStartInfo.FileName = @"C:\Windows\System32\cmd.exe";
cmdStartInfo.RedirectStandardOutput = true;
cmdStartInfo.RedirectStandardError = true;
cmdStartInfo.RedirectStandardInput = true;
cmdStartInfo.UseShellExecute = false;
cmdStartInfo.CreateNoWindow = true;
Process cmdProcess = new Process();
cmdProcess.StartInfo = cmdStartInfo;
cmdProcess.ErrorDataReceived += cmd_Error;
cmdProcess.OutputDataReceived += cmd_DataReceived;
cmdProcess.EnableRaisingEvents = true;
cmdProcess.Start();
cmdProcess.BeginOutputReadLine();
cmdProcess.BeginErrorReadLine();
cmdProcess.StandardInput.WriteLine("ping www.bing.com"); //Execute ping bing.com
cmdProcess.StandardInput.WriteLine("exit"); //Execute exit.
cmdProcess.WaitForExit();
}
static void cmd_DataReceived(object sender, DataReceivedEventArgs e)
{
Console.WriteLine("Output from other process");
Console.WriteLine(e.Data);
}
static void cmd_Error(object sender, DataReceivedEventArgs e)
{
Console.WriteLine("Error from other process");
Console.WriteLine(e.Data);
}
}
}
不錯,不知道那些事件! :) – 2011-03-20 09:52:57
非常感謝你........它真的做我所需要的......;) – Q8Y 2011-03-20 10:49:55
我發現對於某些進程,最好以這種方式執行命令以確保進程將退出執行後:'cmdProcess.StandardInput.WriteLine(「ping www.bing.com && exit」);' – Gobe 2015-02-05 19:23:51