This is a sample program that starts a process, and reads standard output, character by character and not line by line:
static void Main(string[] args)
{
var process = new Process();
process.StartInfo = new ProcessStartInfo(@"C:\Windows\System32\cmd.exe", "/c dir");
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardOutput = true;
process.Start();
var outReader = process.StandardOutput;
while (true)
{
if (!outReader.EndOfStream)
Console.Write((char)outReader.Read() + ".");
if (outReader.EndOfStream)
Thread.Sleep(1);
}
}
A small disclaimer--this was knocked up in no time, and I haven't proved out the issues around timing (what if the process exits before we've grabbed standard output -- very unlikely, I know). As far as your particular issue is concerned however, it shows that one doesn't need to read line by line (you're dealing with a StreamReader
after all).
UPDATE: As per suggestions, included a Thread.Sleep(1)
to yield the thread. Apparently there are issues with using Thread.Sleep(0)
, despite MSDN documentation on the matter (lower priority threads aren't given time). And yes, this is an infinite loop, and there'd have to be some thread management stuff involved to finish-off once the process has completed.