技術とか戦略とか

IT技術者が技術や戦略について書くブログです。

C#:外部コマンド呼び出しの方法

javaプログラムからの外部コマンド呼び出しは別の記事に掲載したのですが、C#でも同様に外部コマンド呼び出しが可能です。
プライベートで「画面から外部コマンドを呼び出し、外部コマンドで出力されたファイルを取り込む」というプログラムを作る予定があるので、それをWindows Fromで実現してみます。
 
【サンプルプログラム】
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

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

    private void button1_Click(object sender, EventArgs e)
    {
      // プロセスを定義
      Process p = new Process();
      p.StartInfo.FileName = @"C:\tmp\HelloWorld.bat";
      p.StartInfo.Arguments = "";

      // プロセス実行
      p.Start();

      // プロセス終了待ち
      p.WaitForExit();

      // 資源を開放
      p.Close();

      // 呼び出したバッチで生成されたファイルを読み込む
      using (StreamReader sr = new StreamReader(
        @"C:\tmp\a.txt", Encoding.GetEncoding("Shift_JIS")))
      {
        label1.Text = sr.ReadLine();
      }
    }
  }
}
 
【呼び出されるバッチ】
・C:\tmp\HelloWorld.bat
@echo off
echo Hello World!> C:\tmp\a.txt
exit 0
 
【実行結果】

f:id:akira2kun:20200924224447j:plain



 f:id:akira2kun:20200924224645j:plain