如何运行控制台应用程序,捕获输出并将其显示在Literal中?
我看到我可以使用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 outputLines = new List(); 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; } }
我做了一些与你的解决方案非常相似的东西 – 这对我来说很好:
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()。
上述就是C#学习教程:如何运行控制台应用程序,捕获输出并将其显示在Literal中?分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/cdevelopment/998446.html