Problem with printing process input in .Net

Viewed 26

Can anyone help me. I've been trying for almost 1 hours but can't still find solution.

I wanted to print the input in the same line and clear the previous line. I've tried to do Console.WriteLine(line.Data + "\r") but it's only printing everything with in the same line and not clearing the previous line

using var p = new Process() {
    StartInfo = new ProcessStartInfo() {
        FileName = binaryName,
        Arguments = arguments,
        RedirectStandardInput = true,
        RedirectStandardOutput = true,
        RedirectStandardError = true,
        UseShellExecute = false,
        CreateNoWindow = true
    },
};
p.EnableRaisingEvents = true;

p.OutputDataReceived += (_, line) => {
    if (!string.IsNullOrEmpty(line.Data)) {
        WriteLine(line.Data);
    }
};
p.ErrorDataReceived += (_, line) => {
    if (!string.IsNullOrEmpty(line.Data))
        SbError.AppendLine(line.Data + Environment.NewLine);
};
p.Start();
p.BeginErrorReadLine();
p.BeginOutputReadLine();
await p.WaitForExitAsync();
return SbError.ToString();

The output became like this (I'm running Aria2c)

[#010580 0B/0B CN:1 DL:0B]

[#010580 304KiB/97MiB(0%) CN:32 DL:461KiB ETA:3m35s]

[#010580 9.5MiB/97MiB(9%) CN:32 DL:5.9MiB ETA:14s]

[#010580 13MiB/97MiB(13%) CN:32 DL:5.0MiB ETA:16s]

[#010580 30MiB/97MiB(31%) CN:32 DL:8.4MiB ETA:7s]

1 Answers

I just tested this code:

Console.Write("This is the first long line.");
Console.WriteLine();
Console.Write("This is the second long line.");
Console.WriteLine();
Console.Write("This is the third long line.");
Console.Write($"\r{new string(' ', 80)}\r");
Console.Write("Short line.");
Console.WriteLine();
Console.Write("This is the fourth long line.");
Console.WriteLine();

and I got this output:

This is the first long line.
This is the second long line.
Short line.
This is the fourth long line.

so I think that that demonstrates how to clear the current line and enable writing to it again. I'd probably put it in a method, e.g.

static void ClearCurrentLine()
{
    Console.Write($"\r{new string(' ', 80)}\r");
}
Related