首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >从.NET应用程序(C#)捕获控制台输出

从.NET应用程序(C#)捕获控制台输出
EN

Stack Overflow用户
提问于 2008-10-09 11:27:15
回答 5查看 142.4K关注 0票数 143

如何从.NET应用程序调用控制台应用程序并捕获控制台中生成的所有输出?

(请记住,我不想先将信息保存在文件中,然后重新列出,因为我希望实时接收它。)

EN

回答 5

Stack Overflow用户

回答已采纳

发布于 2008-10-09 11:32:03

使用ProcessStartInfo.RedirectStandardOutput属性可以很容易地实现这一点。完整的示例包含在链接的MSDN文档中;唯一的警告是,您可能还必须重定向标准错误流才能查看应用程序的所有输出。

代码语言:javascript
复制
Process compiler = new Process();
compiler.StartInfo.FileName = "csc.exe";
compiler.StartInfo.Arguments = "/r:System.dll /out:sample.exe stdstr.cs";
compiler.StartInfo.UseShellExecute = false;
compiler.StartInfo.RedirectStandardOutput = true;
compiler.Start();    

Console.WriteLine(compiler.StandardOutput.ReadToEnd());

compiler.WaitForExit();
票数 178
EN

Stack Overflow用户

发布于 2008-10-09 11:32:20

在创建控制台进程时,使用ProcessInfo.RedirectStandardOutput重定向输出。

然后,您可以使用Process.StandardOutput读取程序输出。

第二个链接有一个如何做到这一点的示例代码。

票数 13
EN

Stack Overflow用户

发布于 2013-03-31 09:36:21

ConsoleAppLauncher是专门为回答这个问题而开发的开源库。它捕获控制台中生成的所有输出,并提供简单的界面来启动和关闭控制台应用程序。

每当控制台向标准/错误输出写入新行时,都会触发ConsoleOutput事件。这些行被排队,并保证遵循输出顺序。

也可作为NuGet package使用。

获取完整控制台输出的示例调用:

代码语言:javascript
复制
// Run simplest shell command and return its output.
public static string GetWindowsVersion()
{
    return ConsoleApp.Run("cmd", "/c ver").Output.Trim();
}

具有实时反馈的示例:

代码语言:javascript
复制
// Run ping.exe asynchronously and return roundtrip times back to the caller in a callback
public static void PingUrl(string url, Action<string> replyHandler)
{
    var regex = new Regex("(time=|Average = )(?<time>.*?ms)", RegexOptions.Compiled);
    var app = new ConsoleApp("ping", url);
    app.ConsoleOutput += (o, args) =>
    {
        var match = regex.Match(args.Line);
        if (match.Success)
        {
            var roundtripTime = match.Groups["time"].Value;
            replyHandler(roundtripTime);
        }
    };
    app.Run();
}
票数 8
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/186822

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档