I’m trying to retrieve the output lines generated by a process I started, here’s the code
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
foreach (myData singleJob in e.Argument as List<myData>)
{
ProcessStartInfo psi = new ProcessStartInfo("myCommandLineProgram.exe");
psi.Arguments = "\"" + singleJob.row + "\"";
psi.CreateNoWindow = true;
psi.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
psi.RedirectStandardInput = true;
psi.RedirectStandardOutput = true;
psi.RedirectStandardError = true;
psi.UseShellExecute = false;
Process p = new Process();
p.StartInfo = psi;
p.Start();
StreamReader sr = p.StandardOutput ;
string line;
while ((line = sr.ReadLine()) != null )
{
this.Invoke((MethodInvoker)delegate
{
richTextBox1.AppendText(sr.ReadLine() + Environment.NewLine);
richTextBox1.ScrollToCaret();
});
}
//StreamReader streamOutput = p.StandardOutput;
//string content = streamOutput.ReadToEnd();
//this.Invoke((MethodInvoker)delegate
//{
// richTextBox1.AppendText(content + Environment.NewLine);
//});
p.WaitForExit();
}
}
While the commented out code is always working (but it doesn’t parse line by line), the code above is somehow faulty, indeed some lines fail to appear into the richtextbox and some others are blank.
Thanks
Shouldn’t that be something like
(
lineinstead ofsr.ReadLine())?Calling
readLine()twice will discard every second line.Also, since you’re calling
ReadLinein the delegate you cannot control when the read occurs. It might be that there were severalReadLines()(from thewhileline) in between.Note, that you should also NOT use the
linevariable: This variable always references the same line variable in the loop, this one might contain new content at the time theAppendTextis executed. You should introduce a new local variable inside the loop like