Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/21.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 调用CLI exe而不返回输出的进程_C#_.net_Command Line_Process_Command Line Interface - Fatal编程技术网

C# 调用CLI exe而不返回输出的进程

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

我有一个应用程序正在做一些视频处理

在处理之前,我需要分析媒体

ffmpeg实用程序
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以将输出发送到事件处理程序。您可能应该用一个代码示例来回答一个新问题,很难说。