如何处理使用控制字符的控制台应用程序的输出?

我想调用一个可执行文件(在我的例子中,这是PNGOUT.exe)并从stdout获取其输出。 但事实certificate它很棘手 – 应用程序使用某种控制字符来替换以前打印的输出(显示进度),C#类愉快地记录它们,当我想分析输出字符串时,我会非常头疼。 (我花了一段时间才弄清楚我的字符串发生了什么)

我用以下方法调用可执行文件:

public static string RunPNGOut(string pngOutPath, string target) { var process = new Process { StartInfo = { UseShellExecute = false, RedirectStandardOutput = true, CreateNoWindow = true, FileName = pngOutPath, Arguments = '"' + target + '"' } }; process.Start(); var result = process.StandardOutput.ReadToEnd(); process.WaitForExit(); return result; } 

我需要使用不同的方法来捕获控制台中的文本的最终状态,或者以某种方式去除result的控制字符(不是简单地删除它们,而是将它们“应用”到字符串以实现最终外观)。 怎么做到呢?

最有可能的是,输出包含\ r \ n,它只是将光标返回到当前行的开头。 如果这是真的,那么你可以通过擦除当前行来相应地调整字符串。 但这并不简单 – 你还必须覆盖前一行。 我将处理一些代码,看看我是否能够找到解决方案。

编辑:这是我提出的解决方案 – 它经过了轻微的测试。 输出将在lines变量中,您可以单独分析或连接在一起进行分析,作为单行。

 string rawOut = "Results:\r\n___ % done\r 10\r 20\r 30\r\nError!"; string[] lines = Regex.Split(rawOut, Environment.NewLine); for(int j=0; j mainLine.Length) mainLine = subLine.ToCharArray(); else subLine.CopyTo(0, mainLine, 0, subLine.Length); } lines[j] = new String(mainLine); } }