首页 文章

如何使用C#读取其他程序的输出?

提问于
浏览
-2

我想从一个名为Testing.exe的程序中获取输出,然后使用另一个程序打印它 .

Testing.exe的输出如下 .

印刷数量:7印刷数量:7

代码如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Testing
{
    class Program
    {
        static int printNumber(int numberToPrint)
        {
            numberToPrint = 7;
            Console.WriteLine("Printing number: " + numberToPrint.ToString());
            return numberToPrint;
        }

        static void Main(string[] args)
        {
            int number = 5;
            number = printNumber(number);
            Console.WriteLine("Printing number: " + number.ToString());
            Console.ReadKey();
        }
    }
}

据说我可以使用Process类和RedirectStandardOutput,但我无法弄清楚如何使用它们......

如何获取上面的输出,并从其他应用程序打印?我试图从控制台应用程序获取输入并将其放入另一个应用程序 .

我刚开始学习编程,所以我很迷茫 .

1 回答

  • 3
    // Start the child process.
     Process p = new Process();
     // Redirect the output stream of the child process.
     p.StartInfo.UseShellExecute = false;
     p.StartInfo.RedirectStandardOutput = true;
     p.StartInfo.FileName = "Write500Lines.exe";
     p.Start();
     // Do not wait for the child process to exit before
     // reading to the end of its redirected stream.
     // p.WaitForExit();
     // Read the output stream first and then wait.
     string output = p.StandardOutput.ReadToEnd();
     p.WaitForExit();
    

    http://msdn.microsoft.com/en-us/library/system.diagnostics.process.standardoutput.aspx

相关问题