I have a C# program that I want to have run an external program and while the program is running, it needs to read the console output and send it in JSON format to a server. This is what I was thinking. Will it work?
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);
}
}
It’s better to use Process.OutputDataReceived event of
Processclass, to not block execution of the program, and do not run the code insidewhile(true)loop !.If main program just has to stand and wait for this process exit, can do