[英]Cannot get the output of command line in c#
我想在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;
,控制台上根本不會打印任何文字,為什么會這樣? 我認為該行只會停止創建新窗口。
移動字符串輸出= 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();`
我會嘗試以下方法:
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();
}
我還建議您看看MS文檔中給出的此示例中的BeginReadOutputLine
方法。 由於是異步的,即使您使用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);
}
}
換那兩條線怎么樣?
p.WaitForExit();
string output = p.StandardOutput.ReadToEnd();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.