I'm running a program using command line in c# this program produce some logs while its running in need to display this logs whenever it get change. I wrote the following code but it shows all the logs once the process has been killed and during the running time my program is not responding. how can I fix it?
regards
ProcessStartInfo procStartInfo = new System.Diagnostics.ProcessStartInfo("cmd", "/c " + "C:\\server.py");
Process proc = new Process();
procStartInfo.WindowStyle = ProcessWindowStyle.Hidden;
procStartInfo.UseShellExecute = false;
procStartInfo.RedirectStandardOutput = true;
//procStartInfo.CreateNoWindow = true;
proc.StartInfo = procStartInfo;
proc.Start();
string output = proc.StandardOutput.ReadToEnd();
proc.WaitForExit(300);
LogstextBox.Text = output;
Edited:
well, I tried to use OutputDataReceived
but it doesn't show any result, here is the changed code:
{
//processCaller.FileName = @"ping";
//processCaller.Arguments = "4.2.2.4 -t"; this is working
processCaller.FileName = @"cmd.exe";
processCaller.Arguments = "/c c:\\server.py"; //this is not working
processCaller.StdErrReceived += new DataReceivedHandler(writeStreamInfo);
processCaller.StdOutReceived += new DataReceivedHandler(writeStreamInfo);
processCaller.Completed += new EventHandler(processCompletedOrCanceled);
processCaller.Cancelled += new EventHandler(processCompletedOrCanceled);
this.richTextBox1.Text = "Server Started.." + Environment.NewLine;
processCaller.Start();
}
private void writeStreamInfo(object sender, DataReceivedEventArgs e)
{
this.richTextBox1.AppendText(e.Text + Environment.NewLine);
}
You can use the Process.BeginOutputReadLine Method. The link shows a complete working example in C# which uses the
OutputDataReceived event
. That code example should do what you want.This is the problem:
You won't get to the "end" of standard output until the process has terminated.
You should be reading a line at a time - or possibly just subscribing to the
OutputDataReceived
event (and following the documented other requirements for that event).EDIT: Here's sample code which works for me:
Note that in your sample code, you're accessing the UI on whatever thread the
OutputDataReceived
handler is called - that looks like a bad idea to me.