How to work with outputs from console applications that use control characters?

I want to call an executable file (in my case it is PNGOUT.exe) and grab its output from stdout. But it turned out to be difficult: the application uses some control characters to replace the previously printed output (displaying progress), and the C # classes happily write them, and when I want to parse the output string, I get a serious headache. (It even took me a while to figure out what was going on with my string)

I call the executable with the following method:

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 ( , "" ). ?

+2
1

, \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);
    }
}
+1

All Articles