你必须给你的进程一个 ProcessStartInfo 告诉它你将要读取输出。
这是一个例子:
ProcessStartInfo startinfo = new ProcessStartInfo();
startinfo.FileName = @"C:\Users\mehmetcan\Desktop\adt-bundle-windows-x86-20130917\sdk\platform-tools\adb.exe";
startinfo.Arguments = @"devices";
startinfo.RedirectStandardOutput = true;
startinfo.RedirectStandardError = true;
// Note: declare process as a variable in the class as it needs to be used in the event handlers
process = new Process();
process.StartInfo = startinfo;
process.OutputDataReceived += process_DataReceived;
process.ErrorDataReceived += process_DataReceived;
process.Start();
process.BeginOutputReadLine();
process.BeginErrorReadLine();
然后是接收数据的事件处理程序(每次流程输出时都会调用它):
private void process_DataReceived(object sender, DataReceivedEventArgs e)
{
// null data means we've received everything
if (e.Data == null) {
process.CancelOutputRead();
process.CancelErrorRead();
return;
}
// e.Data is the string with the output from the process
Console.Write(e.Data);
}
请注意,process_DataReceived
每当进程输出某些内容时都会调用它,如果您需要获得完整的输出,那么您可以这样做:
process_output = ""; // reset output before starting the process
ProcessStartInfo startinfo = new ProcessStartInfo();
startinfo.FileName = @"C:\Users\mehmetcan\Desktop\adt-bundle-windows-x86-20130917\sdk\platform-tools\adb.exe";
startinfo.Arguments = @"devices";
startinfo.RedirectStandardOutput = true;
startinfo.RedirectStandardError = true;
Process process = new Process();
process.StartInfo = startinfo;
process.OutputDataReceived += process_DataReceived;
process.ErrorDataReceived += process_DataReceived;
process.Start();
process.BeginOutputReadLine();
process.BeginErrorReadLine();
// check end of answer if you need to wait for the process to terminate
声明一个对process_DataReceived
和都可用的字符串变量,process_Exited
例如包含方法的类中的变量:
string process_output; // will accumulate the output of the process
然后是事件处理程序:
private void process_DataReceived(object sender, DataReceivedEventArgs e)
{
// null data means we've received everything
if (e.Data == null) {
process.CancelOutputRead();
process.CancelErrorRead();
// do something with the output:
Console.Write(process_output);
return;
}
// append the output to the accumulator
process_output += e.Data;
}
进程退出后,您仍然可以接收到输出数据,因此如果您需要等待进程完成,您可以添加一个标志(一个布尔值),并且只有当您收到空数据时才将其设置为 false process_DataReceived
。只有在发生这种情况时,您才能确保您已收到流程的所有输出。
从“process_DataReceived”访问 UI
如果您必须访问 UI 元素,process_DataReceived
您可以使用它的调度程序来完成。这是一个例子:
private void process_DataReceived(object sender, DataReceivedEventArgs e)
{
// null data means we've received everything
if (e.Data == null) {
process.CancelOutputRead();
process.CancelErrorRead();
// with WPF:
mylabel.Dispatcher.Invoke(new Action(() => {
mylabel.Content = process_output;
}));
// with WinForms
mylabel.Invoke((MethodInvoker) (() =>
{
mylabel.Text = process_output;
}));
return;
}
// append the output to the accumulator
process_output += e.Data;
}