I\'m developing a C# application and I need to start an external console program to perform some tasks (extract files). What I need to do is to redirect the output
Jon said "I'm not sure what "updating" the output means in your case" and I don't know what it means for him either. So I wrote a program that can be used for redirection of its output so we can clearly define the requirements.
It is possible to move the cursor in a console using the Console.CursorLeft Property. However when I used that I was unable to redirect the output, I got an error; something about an invalid stream I think. So then I tried backspace characters, as has already been suggested. So the program I am using to redirect the out from is the following.
class Program
{
static readonly string[] Days = new [] {"Monday", "Tuesday", "Wednesday",
"Thursday", "Friday", "Saturday", "Sunday"};
static int lastlength = 0;
static int pos = 0;
static void Main(string[] args)
{
Console.Write("Status: ");
pos = Console.CursorLeft;
foreach (string Day in Days)
{
Update(Day);
}
Console.WriteLine("\r\nDone");
}
private static void Update(string day)
{
lastlength = Console.CursorLeft - pos;
Console.Write(new string((char)8, lastlength));
Console.Write(day.PadRight(lastlength));
Thread.Sleep(1000);
}
}
When I use the accepted answer to redirect the output of that it works.
I was using some sample code for something entirely different and it was able to process standard output as soon as it is available as in this question. It reads standard output as binary data. So I tried that and the following is an alternative solution for here.
class Program
{
static Stream BinaryStdOut = null;
static void Main(string[] args)
{
const string TheProgram = @" ... ";
ProcessStartInfo info = new ProcessStartInfo(TheProgram);
info.RedirectStandardOutput = true;
info.UseShellExecute = false;
Process p = Process.Start(info);
Console.WriteLine($"Started process {p.Id} {p.ProcessName}");
BinaryStdOut = p.StandardOutput.BaseStream;
string Message = null;
while ((Message = GetMessage()) != null)
Console.WriteLine(Message);
p.WaitForExit();
Console.WriteLine("Done");
}
static string GetMessage()
{
byte[] Buffer = new byte[80];
int sizeread = BinaryStdOut.Read(Buffer, 0, Buffer.Length);
if (sizeread == 0)
return null;
return Encoding.UTF8.GetString(Buffer);
}
}
Actually, this might not be any better than the answer from marchewek but I suppose I will leave this here anyway.