繁体   English   中英

无法在C#中获取命令行的输出

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM