不要对输出进行交互,也不要阅读它!通常你不知道输出有多长(错误输出也是如此),所以你需要准备一个未知的长度。既然你告诉 Process 类,你想自己处理标准输出和标准错误,你还需要bind to the events,在这种情况下:
- OutputDataReceived
- 错误数据接收
或者像@Dmitry Kurilo 在他的回答中所做的那样阻止当前进程并立即读取完整的输出。我发现第一种方法更好,因为我不需要等待过程结束才能看到它的输出。 ProcessStartInfo.RedirectstandardError property 的 MSDN 文档通过大量示例很好地解释了不同的可能性。
如果你想走特定的路线,有很多可能性。一种是将每个输出(行)存储在委托中并稍后使用它,使用 List(Of String) 并在处理完成时输出特定行(= 所有输出行都存在)。
可能的解决方案如下所示:
' store error output lines
dim lines = new List(of String)
dim executable = "c:\temp\android\sdk\platform-tools\adb.exe"
dim arguments = " help"
dim process = new Process()
process.StartInfo = createStartInfo(executable, arguments)
process.EnableRaisingEvents = true
addhandler process.Exited, Sub (ByVal sender As Object, ByVal e As System.EventArgs)
Console.WriteLine(process.ExitTime)
Console.WriteLine(". Processing done.")
' output line n when output is ready (= all lines are present)
Console.WriteLine(lines(4))
end sub
' catch standard output
addhandler process.OutputDataReceived, Sub (ByVal sender As Object, ByVal e As System.Diagnostics.DataReceivedEventArgs)
if (not String.IsNullOrEmpty(e.Data))
Console.WriteLine(String.Format("{0}> {1}", DateTime.Now.ToString("dd.MM.yyyy HH:mm:ss") ,e.Data))
end if
end sub
' catch errors
addhandler process.ErrorDataReceived, Sub (ByVal sender As Object, ByVal e As System.Diagnostics.DataReceivedEventArgs)
'Console.WriteLine(String.Format("! {0}", e.Data))
' add every output line to the list of strings
lines.Add(e.Data)
end sub
' start process
dim result = process.Start()
' and wait for output
process.BeginOutputReadLine()
' and wait for errors :-)
process.BeginErrorReadLine()
private function createStartInfo(byval executable as String, byval arguments as String) as ProcessStartInfo
dim processStartInfo = new ProcessStartInfo(executable, arguments)
processStartInfo.WorkingDirectory = Path.GetDirectoryName(executable)
' we want to read standard output
processStartInfo.RedirectStandardOutput = true
' we want to read the standard error
processStartInfo.RedirectStandardError = true
processStartInfo.UseShellExecute = false
processStartInfo.ErrorDialog = false
processStartInfo.CreateNoWindow = true
return processStartInfo
end function
现在即使 adb 写入错误输出,您也可以看到它。它也将完成。
本例中的输出如下所示:
14.10.2014 12:49:10
. Processing done.
-e - directs command to the only running emulator.
另一种可能性是将所有内容放入一个字符串中,并在该过程完成后将单个字符串拆分为行尾(CRLF \r\n),您将获得要过滤的行。