2014-07-08 84 views
1

我想獲取c#中的執行輸出,我參考了this question。但我只有輸出打印在控制檯上,但沒有存儲在指定的字符串中。這裏是我的代碼:`無法獲得c#中命令行的輸出#

 System.Diagnostics.Process p = new System.Diagnostics.Process(); 
     p.StartInfo.UseShellExecute = false; 
     p.StartInfo.RedirectStandardOutput = true; 
     //p.StartInfo.CreateNoWindow = true; 

     p.StartInfo.FileName = "ffmpeg.exe"; 
     p.StartInfo.Arguments = " -i 1.flv"; 
     p.Start(); 


     p.WaitForExit(); 
     string output = p.StandardOutput.ReadToEnd(); 
     Console.WriteLine(output); 
     Console.ReadLine();` 

執行這些代碼後,輸出字符串仍爲空。此外,如果我保留p.StartInfo.CreateNoWindow = true;這一行,那麼控制檯上將不會打印任何單詞,爲什麼會發生這種情況?我認爲該行只會停止創建一個新窗口。

+0

您是否試過在循環中讀取並監視進程狀態而不是使用'WaitForExit'?我假定在進程退出後,標準輸出流將被關閉。我有一個類似的問題:我從一個Windows服務啓動了一個控制檯應用程序,並希望在標準服務器上發送命令以在服務停止時關閉該應用程序。發生了什麼事是服務意外停止,而不是意外關閉流的異常,控制檯應用程序一直在100%CPU循環中讀空行。 –

回答

0

我會嘗試以下方法:

System.Diagnostics.Process p = new System.Diagnostics.Process(); 
p.StartInfo.UseShellExecute = false; 
p.StartInfo.RedirectStandardOutput = true; 

p.StartInfo.FileName = "ffmpeg.exe"; 
p.StartInfo.Arguments = " -i 1.flv"; 
p.Start(); 

while (!p.HasExited) 
{ 
    string output = p.StandardOutput.ReadToEnd(); 
} 

我也建議你看看在this example given in the MS documentationBeginReadOutputLine方法。即使您使用WaitForExit,它也會被稱爲異步。

一個煮下來的這個版本是:

// Start the asynchronous read of the output stream. 
p.OutputDataReceived += new DataReceivedEventHandler(OutputHandler); 
p.EnableRaisingEvents = true; 
p.BeginOutputReadLine(); 
p.Start(); 
p.WaitForExit(); 
p.Close(); 

private static void OutputHandler(object sendingProcess, DataReceivedEventArgs outLine) 
{ 
    // Collect the command output. 
    if (!String.IsNullOrEmpty(outLine.Data)) 
    { 
     numOutputLines++; 

     // Add the text to the output 
     Console.WriteLine(Environment.NewLine + 
       "[" + numOutputLines.ToString() + "] - " + outLine.Data); 
    } 
} 
+0

感謝您的幫助,但我發現問題可能來自執行ffmpeg本身,所以無論是同步或異步方法是可行的。我嘗試了像「ping」和「ipconfig」這樣的命令,它們都運行良好。@ ThorstenDittmar –

1

移動字符串輸出= p.StandardOutput.ReadToEnd();裏面等待退出。 如何在數據已經退出時讀取數據。

System.Diagnostics.Process p = new System.Diagnostics.Process(); 
    p.StartInfo.UseShellExecute = false; 
    p.StartInfo.RedirectStandardOutput = true; 
    //p.StartInfo.CreateNoWindow = true; 

    p.StartInfo.FileName = "ffmpeg.exe"; 
    p.StartInfo.Arguments = " -i 1.flv"; 
    p.Start(); 
    string output = p.StandardOutput.ReadToEnd(); 
    p.WaitForExit(); 

    Console.WriteLine(output); 
    Console.ReadLine();` 
+0

這不會有幫助,因爲他不會得到整個輸出。 'ReadToEnd'讀取當時可用的內容,然後繼續。 –

+0

是的輸出是相同的 –

0

如何切換這兩個行?

p.WaitForExit(); 
string output = p.StandardOutput.ReadToEnd();