C#用Process执行命令行程序,现在可以做到获取整个命令行输出结果。但新的问题是:命令行程序执行时间较长,如果等到结束再获取输出,对于下面的问题将是浪费时间。
现在想要达到的效果是:随时获取输出并检索其内容,一旦发现特定的输出信息(如错误信息字符串),就强行终止命令行程序的执行并返回已经获取的输出(尽管只是部分输出),不要等到程序执行结束。请提供相关线索或示例。
现在想要达到的效果是:随时获取输出并检索其内容,一旦发现特定的输出信息(如错误信息字符串),就强行终止命令行程序的执行并返回已经获取的输出(尽管只是部分输出),不要等到程序执行结束。请提供相关线索或示例。
public partial class Form1 : Form
{
private static StringBuilder sortOutput = null;
private static int numOutputLines = 0;
private void button1_Click(object sender, EventArgs e)
{
// 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.FileName = "cmd.exe";
p.StartInfo.Arguments = "/c dir c:\\"; p.OutputDataReceived += new DataReceivedEventHandler(SortOutputHandler); sortOutput = new StringBuilder("");
p.Start(); p.BeginOutputReadLine();
// 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.
//string output = p.StandardOutput.ReadToEnd();
p.WaitForExit();
} private void SortOutputHandler(object sendingProcess,
DataReceivedEventArgs outLine)
{
// Collect the sort command output.
if (!String.IsNullOrEmpty(outLine.Data))
{
numOutputLines++; // Add the text to the collected output.
sortOutput.Append(Environment.NewLine +
"[" + numOutputLines.ToString() + "] - " + outLine.Data); if (outLine.Data.EndsWith("temp"))
{
((Process)sendingProcess).Close();
}
}
}
}参考:
http://msdn.microsoft.com/en-us/library/system.diagnostics.process.outputdatareceived.aspx