Reputation: 113
I am looking for a way to read the standard output byte by byte from an external command line application.
The current code works, but only when a newline is added. Is there a way to read the current line input byte by byte so I can update the user with progress.
Ex)
Proccesing file 0% 10 20 30 40 50 60 70 80 90 100% |----|----|----|----|----|----|----|----|----|----| xxxxxx
A x is added every few minutes in the console application but not in my c# Win form as it only updates when it has completed with the current line (the end)
Sample code:
Process VSCmd = new Process();
VSCmd.StartInfo = new ProcessStartInfo("c:\\testapp.exe");
VSCmd.StartInfo.Arguments = "--action run"
VSCmd.StartInfo.RedirectStandardOutput = true;
VSCmd.StartInfo.RedirectStandardError = true;
VSCmd.StartInfo.UseShellExecute = false;
VSCmd.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
VSCmd.StartInfo.CreateNoWindow = true;
VSCmd.Start();
StreamReader sr = VSCmd.StandardOutput;
while ((s = sr.ReadLine()) != null)
{
strLog += s + "\r\n";
invoker.Invoke(updateCallback, new object[] { strLog });
}
VSCmd.WaitForExit();
Upvotes: 3
Views: 1377
Reputation: 53699
The following will build up strLog character by character, I assumed you wanted to invoke updateCallback for each line, of course if this is not the case then you can remove the check for new line.
int currChar;
int prevChar = 0;
string strLog = string.Empty;
while ((currChar = sr.Read()) != -1)
{
strLog += (char)currChar; // You should use a StringBuilder here!
if (prevChar == 13 && currChar == 10) // Remove if you need to invoke for each char
{
invoker.Invoke(updateCallback, new object[] { strLog });
}
prevChar = currChar;
}
Upvotes: 0
Reputation: 41223
Try to use StreamReader.Read()
to read the next available character from the stream without waiting for the full line. This function returns an int
that is -1 is the end of the stream has been reached, or can be cast to a char
otherwise.
Upvotes: 2