2011-05-27 59 views
2

我使用Process類調用控制檯應用程序。我正在將輸出重定向到一個日誌文件,但是當我沒有重定向輸出時,控制檯窗口中的消息比我在日誌文件中時多。任何想法爲什麼?爲什麼在從進程重定向時缺少輸出?

ProcessStartInfo psi = new ProcessStartInfo(); 
string filename = @"ProgrammingMaster_LocalPowertrain.exe"; 
psi.FileName = filename; 
string arguments = String.Format("{0} {1} false", InstanceId.ToString(), ManifestFolderPath); 
psi.Arguments = arguments; 
LogMessage(msgType.Warning, filename + " - " + arguments); 
psi.UseShellExecute = false; 
psi.CreateNoWindow = true; 
psi.RedirectStandardError = true; 
psi.RedirectStandardOutput = true; 
FBlockProcess = new Process(); 
FBlockProcess.StartInfo = psi; 
FBlockProcess.OutputDataReceived += new DataReceivedEventHandler(FBlockProcess_OutputDataReceived); 
FBlockProcess.ErrorDataReceived += new DataReceivedEventHandler(FBlockProcess_ErrorDataReceived); 
FBlockProcess.Start(); 
FBlockProcess.BeginOutputReadLine(); 
FBlockProcess.BeginErrorReadLine(); 

在我OutputDataReceived處理我的字符串添加到ConcurrentQueue

編輯: 我要補充一點,我想捕捉實時輸出或接近它。這個過程可能需要30多分鐘才能完成,我不想等待很長時間才能看到發生了什麼。

更新: 後的前四線輸出,該OutputDataReceived事件處理程序不會被調用,即使我知道有輸出到控制檯10或15以上線路時,我不重定向。任何想法可能導致什麼?

+0

可能與沖洗流有關嗎? – Nick 2011-05-27 12:09:23

+0

在關閉流之前是否調用WaitForExit()? – codymanix 2011-05-27 12:17:52

+0

@codymanix - no。我認爲使用這些事件會使這種事情變得沒有必要。 – scott 2011-05-27 12:32:56

回答

0

嘗試這個例子:

public static void Main() 
{ 
    Process p = new Process(); 
    p.StartInfo.FileName = "cmd.exe"; 
    p.StartInfo.Arguments = "/c dir *.cs"; 
    p.StartInfo.UseShellExecute = false; 
    p.StartInfo.RedirectStandardOutput = true; 
    p.Start(); 

    string output = p.StandardOutput.ReadToEnd(); 

    Console.WriteLine("Output:"); 
    Console.WriteLine(output);  
} 

更新

我想你可以嘗試有用的東西在這裏:

http://msdn.microsoft.com/en-us/library/system.diagnostics.process.errordatareceived.aspx

更新

我發現這個鏈接, 「解決方案1」聽起來是正確的:

http://www.codeproject.com/Answers/152467/Problem-executing-a-command-line-command-from-Csha.aspx?cmt=49313#answer1

+0

這樣我就不會得到任何的輸出,直到它關閉正確? – scott 2011-05-27 12:25:42

+0

是的,我認爲是這樣的... – danyolgiax 2011-05-27 12:27:41

+0

它看起來像我這樣做的相同方式。你能看到我失蹤的東西嗎? – scott 2011-05-27 12:57:37

0

我嘗試與需要身份驗證的應用程序進行交互時遇到了類似的問題。當遇到時髦字符(unicode字符?)時,Peek()會返回-1,並且ReadLine()也不可靠,並且最終會鎖定我的應用程序,因爲它似乎是標準流未關閉。

使用Read()方法是我可以確保獲得所有行和字符的唯一方法。此外,使用Process'ErrorDataReceived或OutputDataReceived事件處理程序也證明不可靠(缺少行)。以下是我如何解決我的問題,並確保所有行和字符都已收到:

process.Start(); 
var stdOutput = process.StandardOutput; 
StringBuilder fullMessage = new StringBuilder(); 
while (true) 
{ 
    var character = (char)stdOutput.Read(); 
    fullMessage.Append(character); 

    //Print Out All Characters 
    Console.Write(character); 
    if (fullMessage.ToString().EndsWith("Enter Password: ")) 
    { 
     //Submit Password To Application 
     using(StreamWriter writer = process.StandardInput){ 
      writer.Write("somepassword"); 
      writer.Flush(); 
     } 

     break; 
    } 
} 
相關問題