首页 >后端开发 >C++ >如何从C#中的.NET应用程序中捕获实时控制台输出?

如何从C#中的.NET应用程序中捕获实时控制台输出?

Barbara Streisand
Barbara Streisand原创
2025-01-29 12:21:12631浏览

How to Capture Real-time Console Output from .NET Applications in C#?

在C#中实时捕获.NET应用程序控制台输出

问题:

.NET应用程序开发者在集成控制台应用程序时,常常面临捕获控制台应用程序生成的输出的挑战。如何在不依赖基于文件的方法的情况下实时捕获此输出?

解决方案:

利用ProcessStartInfo.RedirectStandardOutput属性将控制台应用程序的输出重定向到.NET应用程序中的流。

实现:

以下C#代码片段演示了如何调用控制台应用程序并捕获其输出:

<code class="language-csharp">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();

string output = compiler.StandardOutput.ReadToEnd();
Console.WriteLine(output);

compiler.WaitForExit();</code>

说明:

  • ProcessStartInfo类存储有关要执行的可执行文件的信息。
  • 设置FileNameArguments属性以指定要调用的控制台应用程序。
  • 禁用UseShellExecute以更好地控制进程执行。
  • 启用RedirectStandardOutput将控制台的标准输出重定向到当前进程中的流。
  • 调用Start()执行控制台应用程序。
  • ReadToEnd()读取流直到其结束,捕获控制台应用程序的所有输出。
  • WaitForExit()等待控制台应用程序完成执行后再继续执行。

This revised response maintains the original image and its format while rewording the text for improved clarity and flow. Key terms are also slightly altered to avoid direct copying.

以上是如何从C#中的.NET应用程序中捕获实时控制台输出?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn