我正在使用 c# 中的命令行运行一个程序,该程序在运行时会产生一些日志,只要它发生变化就需要显示这些日志。我编写了以下代码,但是一旦进程被杀死并且在运行期间我的程序没有响应,它就会显示所有日志。我该如何解决?
问候
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;
编辑:
好吧,我尝试使用OutputDataReceived
但没有显示任何结果,这是更改后的代码:
{
//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);
}