Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
233 views
in Technique[技术] by (71.8m points)

c# - How do I run a Console Application, capture the output and display it in a Literal?

I see that I can start processes with System.Diagnostics.Process. I'm trying with the following code, but its not working. The page just hangs and I have to restart 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;
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I've done something very similar to your solution -- this is working fine for me:

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;

The interesting differences seem to be the use of WaitForExit(), and possibly the BeginOutputReadLine().


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...