オンプレ系インフラエンジニアがAzureを勉強する

いつか誰かの何かの役に立つと嬉しいな

.NETコンソールアプリでコマンド実行してみる

はじめに

.NETコンソールアプリで任意のコマンドを実行するexeを作ります。

プロジェクトの作成

下記コマンドでプロジェクトを作成します。
オプションはどちらかひとつでも通ります。
 -o:出力先のディレクトリ名の指定
 -n:プロジェクトファイル名の指定

dotnet new console -o [プロジェクト名]

ソースコード

using System;
using System.Diagnostics;

namespace commandtest
{
    class Program
    {
        static int Main(string[] args)
        {
            int rtn = 0;
            int result = 0;
            try
            {
                // プロセスの起動
                ProcessStartInfo psi = new ProcessStartInfo("cmd.exe", "/k dir");
                // プロセスを新しいウィンドウで起動する
                psi.CreateNoWindow = true;

                // プロセスの起動にシェルを使用する
                psi.UseShellExecute = true;
                psi.RedirectStandardError = false;
                psi.RedirectStandardInput = false;
                psi.RedirectStandardOutput = false;

                // ウィンドウの状態を取得/設定
                psi.WindowStyle = ProcessWindowStyle.Normal;

                // 実行
                using (Process proc = Process.Start(psi))
                {
                    // プロセスの終了を待つ
                    proc.WaitForExit();

                    // プロセスが終了時に指定された値を受け取る
                    result = proc.ExitCode;
                }
            }
            catch
            {
                rtn = -1;
            }
            Environment.ExitCode = rtn;
            return rtn;
        }
    }
}

コード内補足

ProcessStartInfo:引数に起動時に使用するアプリとアプリに渡すコマンドが設定できます。using System.Diagnosticsが必要です。
ProcessStartInfo クラス (System.Diagnostics) | Microsoft Docs

コマンド指定の先頭にある/kは実行後にウィンドウを閉じないために指定します。
ウィンドウを閉じたい場合は/cにします。

RedirectStandardError:アプリケーションのエラー出力を StandardError ストリームに書き込むかを指定します。
ProcessStartInfo.RedirectStandardError プロパティ (System.Diagnostics) | Microsoft Docs

RedirectStandardInput:アプリケーションの入力を StandardInput ストリームから読み取るかを指定します。
ProcessStartInfo.RedirectStandardInput プロパティ (System.Diagnostics) | Microsoft Docs

RedirectStandardOutput:アプリケーションのテキスト出力を StandardOutput ストリームに書き込むかを指定します。
ProcessStartInfo.RedirectStandardOutput プロパティ (System.Diagnostics) | Microsoft Docs

※UseShellExecuteを使用する場合、上記3つはfalseにする必要があります。

WindowStyle:プロセスを起動するときに使用するウィンドウの状態を取得/設定できます。最大化(Maximized)、最小化(Minimized)、通常(Normal) 、非表示(Hidden)が選べます。
ProcessStartInfo.WindowStyle プロパティ (System.Diagnostics) | Microsoft Docs

WaitForExit:指定した時間が経過するかプロセスが終了するまで現在のスレッドの実行をブロックします。
Process.WaitForExit メソッド (System.Diagnostics) | Microsoft Docs

exeで実行できる形にする

dotnet publish -c Release

プロジェクトの下記にビルドされます。
bin\Release\net5.0\publish

exeをダブルクリックすると実行できます。