C# 调用CLI exe而不返回输出的进程
我有一个应用程序正在做一些视频处理 在处理之前,我需要分析媒体 ffmpeg实用程序C# 调用CLI exe而不返回输出的进程,c#,.net,command-line,process,command-line-interface,C#,.net,Command Line,Process,Command Line Interface,我有一个应用程序正在做一些视频处理 在处理之前,我需要分析媒体 ffmpeg实用程序ffprobe.exe提供了我需要的所有信息 但是,我使用的代码不会返回在cmd窗口中运行命令时显示的文本: public static string RunConsoleCommand(string command, string args) { var consoleOut = ""; using (var process = new Process()) { pro
ffprobe.exe
提供了我需要的所有信息
但是,我使用的代码不会返回在cmd
窗口中运行命令时显示的文本:
public static string RunConsoleCommand(string command, string args)
{
var consoleOut = "";
using (var process = new Process())
{
process.StartInfo = new ProcessStartInfo
{
FileName = command,
Arguments = args,
UseShellExecute = false,
CreateNoWindow = true,
RedirectStandardOutput = true
};
process.Start();
consoleOut = process.StandardOutput.ReadToEnd();
process.WaitForExit();
return consoleOut;
}
}
有什么想法吗?Process类有一些事件需要处理:
public static string RunConsoleCommand(string command, string args)
{
var consoleOut = "";
using (var process = new Process())
{
process.StartInfo = new ProcessStartInfo
{
FileName = command,
Arguments = args,
UseShellExecute = false,
CreateNoWindow = true,
RedirectStandardOutput = true
};
// Register for event and do whatever
process.OutputDataReceived += new DataReceivedEventHandler((snd, e) => { consoleOut += e.Data; });
process.Start();
process.WaitForExit();
return consoleOut;
}
}
您还收到了ErrorDataReceived,其工作方式与此相同
我在一些项目中使用了这些活动,效果非常好。希望有帮助
编辑:修复了代码,您需要在启动流程之前附加处理程序。谢谢@T.Fabre您对ErrorDataRevieve的评论是关键。ffmpeg应用程序将其日志输出到此错误流。我发现
RedirectStandardOutput=true
和process.OutputDataReceived+=新DataReceiveDevenHandler((snd,e)=>{consoleOut+=e.Data;})之间存在冲突代码>。我必须删除第一个,我的程序会正确地返回输出,为什么?不太确定。声明应启用RedirectStandardOutput以将输出发送到事件处理程序。您可能应该用一个代码示例来回答一个新问题,很难说。