我想调用一个可执行文件(在我的例子中,这是 PNGOUT.exe)并从标准输出中获取它的输出。但事实证明它很棘手——应用程序使用某种控制字符来替换以前打印的输出(进度显示),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,它只是将光标返回到当前行的开头。如果是这样,那么您可以通过删除当前行来相应地调整字符串。不过这并不简单——您还必须覆盖上一行。我将编写一些代码,看看能否找到解决方案。
编辑:这是我想出的解决方案 - 它经过轻微测试。输出将在 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<lines.Length; j++)
{
string line = lines[j];
if (line.Contains('\r'))
{
string[] subLines = line.Split('\r');
char[] mainLine = subLines[0].ToCharArray();
for(int i=1; i<subLines.Length; i++)
{
string subLine = Regex.Replace(subLines[i], ".\x0008(.)", "$1");
if (subLine.Length > mainLine.Length) mainLine = subLine.ToCharArray();
else subLine.CopyTo(0, mainLine, 0, subLine.Length);
}
lines[j] = new String(mainLine);
}
}
关于c# - 如何处理使用控制字符的控制台应用程序的输出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17513175/