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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/878632/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-05 05:09:25  来源:igfitidea点击:

Best Way to call external program in c# and parse output

c#.net

提问by

Duplicate

复制

Redirect console output to textbox in separate programCapturing nslookup shell output with C#

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

I am looking to call an external program from within my c# code.

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

The program I am calling, lets say foo.exe returns about 12 lines of text.

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

I want to call the program and parse thru the output.

我想调用程序并解析输出。

What is the most optimal way to do this ?

执行此操作的最佳方法是什么?

Code snippet also appreciated :)

代码片段也很受欢迎:)

Thank You very much.

非常感谢您。

采纳答案by Stormenet

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);    
    }
}