使用进程时程序不会终止

时间:2011-06-21 11:28:24

标签: c# process processstartinfo

使用ProcessStartInfoProcess我想启动一个程序(例如getdiff.exe),然后读取程序生成的所有输出。稍后我将以更具建设性的方式使用数据现在我只想打印数据以确保其正常工作。但是程序没有按预期终止。有谁为什么?先谢谢你。

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();

将程序更改为此可以使其正常工作:

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();

4 个答案:

答案 0 :(得分:3)

The MSDN provides a good example如何重定向进程输入/输出。 ReadToEnd()无法正确确定流的结尾。 MSDN says

  

ReadToEnd假设流知道它何时到达终点。对于交互式协议,其中服务器仅在您请求数据时才发送数据并且不关闭连接,ReadToEnd可能会无限期地阻止,应该避免。

编辑: 避免ReadToEnd()的另一个原因:一个非常快的进程将导致异常,因为在程序输出任何数据之前必须重定向流。

答案 1 :(得分:2)

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();

答案 2 :(得分:1)

不确定它是否相关,但你做psi.RedirectStandardInput = true;而没有对结果流做任何事情。也许,不知何故,应用程序要求输入流在退出之前“关闭”?所以试试myProcess.StandardInput.Close()

答案 3 :(得分:0)

请尝试使用此代码,

p.CloseMainWindow()

相关问题