我有一个要运行外部程序的C#程序,并且在该程序运行时,它需要读取控制台输出并将其以JSON格式发送到服务器。这就是我的想法。能行吗
ProcessStartInfo psi = new ProcessStartInfo("app.exe");
psi.RedirectStandardOutput = true;
psi.WindowStyle = ProcessWindowStyle.Hidden;
psi.UseShellExecute = false;
Process app = Process.Start(psi);
while (true)// what do I loop on?
{
string line = "{ \"message\": \"" + app.StandardOutput.ReadLine() + "\" }";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url + "/results/:" + runId + "/logs");
request.ContentType = "text/json";
request.Method = "POST";
using (TextWriter tw = new StreamWriter(request.GetRequestStream()))
{
tw.WriteLine(line);
}
}
最佳答案
最好使用Process
类的Process.OutputDataReceived事件,以免阻止程序执行,并且不要在while(true)
循环中运行代码!
如果主程序只需要站立等待该过程退出,就可以
Process app = Process.Start(psi);
// read code, subscription to event described above,
// and processing it inside event handler
app.WaitForExit();