2011-06-21 96 views
2

使用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(); 
+0

哪一部分沒有結束,因爲它應該?你的應用程序,還是被調用的進程? – Jaymz

+0

爲什麼它應該終止?它是控制檯應用程序?還有別的嗎? –

+0

這是一個更大程序中的功能。但是,單獨運行時,程序永遠不會終止。所以這不健康。 – Teletha

回答

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

不知道它的相關,但你psi.RedirectStandardInput = true;沒有做與得到的東西流。也許,不知何故,應用程序要求輸入流在退出之前「關閉」?所以試試myProcess.StandardInput.Close()

+0

我也看到了。 'psi.RedirectStandardOutput = true;'終止程序。輸出很奇怪,但終止。 – Teletha

3

The MSDN provides a good example過程輸入/輸出如何重定向。 ReadToEnd()無法正確確定流的結束。 MSDN says

ReadToEnd假定流知道它何時到達結束。對於交互式協議,在服務器僅在您請求並且不關閉連接時才發送數據的情況下,ReadToEnd可能會無限期阻塞,應該避免。

編輯: 另一個原因,以避免ReadToEnd():一個非常快的過程將導致異常的,因爲流必須被重定向程序輸出之前的任何數據。

0

試試這個代碼,而不是,

p.CloseMainWindow()