【问题标题】:How do I run a Console Application, capture the output and display it in a Literal?如何运行控制台应用程序、捕获输出并将其显示为文字?
【发布时间】:2011-02-25 20:34:09
【问题描述】:

我发现我可以使用 System.Diagnostics.Process 启动进程。我正在尝试使用以下代码,但它不起作用。页面刚刚挂起,我必须重新启动 IIS...

using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Diagnostics;

public partial class VideoTest : System.Web.UI.Page
{
    List<string> outputLines = new List<string>();
    bool exited = false;

    protected void Page_Load(object sender, EventArgs e)
    {
        string AppPath = Request.PhysicalApplicationPath;

        Process myProcess = new Process();

        myProcess.StartInfo.UseShellExecute = false;
        myProcess.StartInfo.FileName = AppPath + "\\bin\\ffmpeg.exe";
        myProcess.StartInfo.CreateNoWindow = true;
        myProcess.OutputDataReceived += new DataReceivedEventHandler(OutputHandler);
        myProcess.Exited += new EventHandler(ExitHandler);
        myProcess.Start();

        while (!exited)
        {
            // This is bad bad bad bad....
        }

        litTest.Text = "";
        foreach (string line in outputLines)
            litTest.Text += line;
    }

    private void OutputHandler(object sendingProcess, DataReceivedEventArgs outLine)
    {
        outputLines.Add(outLine.Data);
    }

    // Handle Exited event and display process information.
    private void ExitHandler(object sender, System.EventArgs e)
    {
        exited = true;
    }
}

【问题讨论】:

  • 也许您应该先从控制台应用程序测试此代码?
  • 在您可以捕获 ffmpeg.exe 输出的地方,我的应用程序在调用此 exe 期间会阻塞,并且我没有看到任何输出,Exited 事件触发正常。最近的 ffmpeg 是彩色的,所以我不知道它是否会输出到标准输出?另外,我是否必须从线程启动它?如果你有工作,请分享你的最终解决方案,谢谢。

标签: c# asp.net-2.0 system.diagnostics


【解决方案1】:

我做了一些与你的解决方案非常相似的事情——这对我来说很好:

ProcessStartInfo pInfo = new ProcessStartInfo("cmd.exe");
pInfo.FileName = exePath;
pInfo.WorkingDirectory = new FileInfo(exePath).DirectoryName;
pInfo.Arguments = args;
pInfo.CreateNoWindow = false;
pInfo.UseShellExecute = false;
pInfo.WindowStyle = ProcessWindowStyle.Normal;
pInfo.RedirectStandardOutput = true;
Process p = Process.Start(pInfo);
p.OutputDataReceived += p_OutputDataReceived;
p.BeginOutputReadLine();
p.WaitForExit();
// set status based on return code.
if (p.ExitCode == 0) this.Status = StatusEnum.CompletedSuccess;
   else this.Status = StatusEnum.CompletedFailure;

有趣的区别似乎是 WaitForExit() 的使用,可能还有 BeginOutputReadLine()。

【讨论】:

  • 是否有原因在命令行上运行命令需要30秒,但通过这种方法运行需要30-40分钟。
  • 不知道 - 我没有看到这种行为。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-10-27
  • 1970-01-01
  • 2019-09-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多