我有一个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);
}
}
答案 0 :(得分:4)
最好使用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();
答案 1 :(得分:2)
尝试这样的事情:
ProcessStartInfo psi = new ProcessStartInfo("app.exe");
psi.RedirectStandardOutput = true;
psi.WindowStyle = ProcessWindowStyle.Hidden;
psi.UseShellExecute = false;
Process app = Process.Start(psi);
StreamReader reader = app.StandardOutput;
do
{
string line = "{ \"message\": \"" + reader.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);
}
}while(!reader.EndOfStream);
app.WaitForExit();
答案 2 :(得分:1)
我会考虑将输出窗口的重定向更改为事件日志甚至文本文件。然后,让您的Web应用程序定期检查事件日志或文本文件,同时跟踪它停止的位置,然后仅发送新结果。