標準出力(コンソールアプリケーション)の内容をプログラムで受け取る - C#

プログラムから標準出力(コンソールアプリケーションの出力)の内容を受け取りたい場合があります。標準出力を受け取るにはProcessクラスのStartInfo.RedirectStandardOutput プロパティをTrueに設定すると、呼び出し側のアプリケーションで標準出力の内容を受け取れます。

コード例

呼び出し側WinFormアプリケーション (Form1.cs)

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;

namespace ExecCmdProgram
{
  public partial class Form1 : Form
  {
    public Form1()
    {
      InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
      Process process = new Process();
      process.StartInfo.FileName = textBox1.Text;
      
      process.StartInfo.UseShellExecute = false;
      process.StartInfo.RedirectStandardOutput = true; // 標準出力をリダイレクト
       process.StartInfo.CreateNoWindow = true;         // コンソールウィンドウを表示しない 
       process.Start();

      process.WaitForExit();

      string output = process.StandardOutput.ReadToEnd();
      textBox2.Text = output;
      
      process.Close();
    }
  }
}

呼び出される側のコンソールアプリケーション (SimpleConsoleApp - Program.cs)

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

namespace SimpleConsoleApp
{
  class Program
  {
    static void Main(string[] args)
    {
      Console.WriteLine("Penguin");
      Console.WriteLine("Duck");
      Console.WriteLine("Ant");

    }
  }
}

実行結果

実行結果は下図のとおりです。コンソールアプリケーションの実行出力結果がテキストボックスに表示されます。


著者
iPentecのメインプログラマー
C#, ASP.NET の開発がメイン、少し前まではDelphiを愛用
掲載日: 2010-11-12
iPentec all rights reserverd.