header
CodePanic! > C#.NET Tips > 今ここ

■DOSコマンドを実行して結果を得る

System.Diagnostics.Process クラスを利用します。
例ではipconfigコマンドを実行し、その結果を文字列で取得しています。

追記:
fcコマンドでファイルの比較をこの方法で行おうとしたのですが
どうしてもうまくいきませんでした。。。orz
うまくいった方は方法を教えて頂けると参考になります。

>2011.11.01 追記
Hiroさんより掲示板にて情報を頂きました。

UseShellExecute = true;
に設定することで解決できるそうです。

参考:Executing file compare process from C#
http://www.dotnet247.com/247reference/msgs/21/107593.aspx


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

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

        private void button1_Click(object sender, EventArgs e)
        {
            System.Diagnostics.Process pro = new System.Diagnostics.Process();

            pro.StartInfo.FileName = "ipconfig";            // コマンド名
            pro.StartInfo.Arguments = "/all";               // 引数
            pro.StartInfo.CreateNoWindow = true;            // DOSプロンプトの黒い画面を非表示
            pro.StartInfo.UseShellExecute = false;          // プロセスを新しいウィンドウで起動するか否か
            pro.StartInfo.RedirectStandardOutput = true;    // 標準出力をリダイレクトして取得したい

            pro.Start();

            string output = pro.StandardOutput.ReadToEnd();
            output.Replace("\r\r\n", "\n"); // 改行コード変換

            MessageBox.Show(output);
        }
    }
}





Copyright © 2008.07 - shougo suzaki