最佳方法在c#中调用外部程序并解析输出

25 .net c#

重复

在单独的程序中将控制台输出重定向到文本框 使用C#捕获nslookup shell输出

我希望从我的c#代码中调用外部程序.

我调用的程序,假设foo.exe返回大约12行文本.

我想调用程序并通过输出解析.

这样做的最佳方式是什么?

代码片段也赞赏:)

非常感谢你.

Sto*_*net 59

using System;
using System.Diagnostics;

public class RedirectingProcessOutput
{
    public static void Main()
    {
        Process p = new Process();
        p.StartInfo.FileName = "cmd.exe";
        p.StartInfo.Arguments = "/c dir *.cs";
        p.StartInfo.UseShellExecute = false;
        p.StartInfo.RedirectStandardOutput = true;
        p.Start();

        string output = p.StandardOutput.ReadToEnd();
        p.WaitForExit();

        Console.WriteLine("Output:");
        Console.WriteLine(output);    
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 几乎.您需要在ReadToEnd()之后调用WaitForExit(),以避免阻塞问题. (6认同)
  • 在较长的程序中,请记住处理该进程或在`using(Process pProcess = new Process()){}`block中使用它 (5认同)