Using the ProcessStartInfo
and Process
I would like start a program (e g getdiff.exe) and then read all the output that program produces. Later I will use the data in a more constructive way put right now I just want to print the data to ensure it works. However the program doesn’t terminate as it should. Does anyone se why? Thank you in advanced.
ProcessStartInfo psi = new ProcessStartInfo("getdiff.exe");
psi.Arguments = "DIFF";
psi.UseShellExecute = false;
psi.RedirectStandardInput = true;
psi.WorkingDirectory = "c:\\test";
Process p = Process.Start(psi);
string read = p.StandardOutput.ReadToEnd();
p.WaitForExit();
Console.WriteLine(开发者_高级运维p);
Console.WriteLine("Complete");
p.Close();
Changing the program to this got it working correctly:
ProcessStartInfo psi = new ProcessStartInfo("getdiff.exe");
psi.Arguments = "DIFF";
psi.UseShellExecute = false;
psi.RedirectStandardInput = true;
psi.WorkingDirectory = "c:\\test";
Process p = Process.Start(psi);
StreamReader read = p.StandardOutput;
while (read.Peek() >= 0)
Console.WriteLine(read.ReadLine());
Console.WriteLine("Complete");
p.WaitForExit();
p.Close();
ProcessStartInfo psi = new ProcessStartInfo("getdiff.exe");
psi.Arguments = "DIFF";
psi.UseShellExecute = false;
psi.RedirectStandardInput = true;
psi.WorkingDirectory = "c:\\test";
Process p = Process.Start(psi);
StreamReader read = p.StandardOutput;
while (read.Peek() >= 0)
Console.WriteLine(read.ReadLine());
Console.WriteLine("Complete");
p.WaitForExit();
p.Close();
The MSDN provides a good example how a process input/output can be redirected. ReadToEnd()
cannot determine the end of the stream correctly. The MSDN says:
ReadToEnd assumes that the stream knows when it has reached an end. For interactive protocols, in which the server sends data only when you ask for it and does not close the connection, ReadToEnd might block indefinitely and should be avoided.
EDIT:
Another reason to avoid ReadToEnd()
: A very fast process will cause an exception, because the stream has to be redirected BEFORE the program output any data.
Not sure if it's related, but you do psi.RedirectStandardInput = true;
without doing something with the resulting stream. Maybe, somehow, the application requires that the input stream is "closed" before it exits? So try myProcess.StandardInput.Close()
.
Try out this code instead,
p.CloseMainWindow()
精彩评论