3

使用ProcessStartInfoandProcess我想启动一个程序(例如 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

4 回答 4

3
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();
于 2011-06-21T19:52:47.640 回答
3

MSDN 提供了如何重定向流程输入/输出的一个很好的示例。ReadToEnd()无法正确确定流的结尾。MSDN说:

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

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

于 2011-06-21T11:38:18.307 回答
1

不确定它是否相关,但您psi.RedirectStandardInput = true;无需对结果流进行任何操作。也许,不知何故,应用程序要求输入流在退出之前“关闭”?所以试试myProcess.StandardInput.Close()

于 2011-06-21T11:36:26.047 回答
-1

试试这个代码,

p.CloseMainWindow()

于 2011-06-21T11:41:21.050 回答