中堅プログラマーの備忘録

忘れっぽくなってきたので備忘録として・・・

.netアプリケーションでコマンドライン引数を取得する

開発環境:visual studio2015
開発言語:C#

アプリケーション起動時にパラメーターを渡したい場合
【System.Environment.CommandLine】プロパティか
【System.Environment.GetCommandLineArgs() 】メソッドを使用します。

まずはフォームアプリケーションでプロジェクトを作成します。
Main関数を下記のとおり編集します。

static class Program
{
    /// <summary>
    /// アプリケーションのメイン エントリ ポイントです。
    /// </summary>
    [STAThread]
    static void Main()
    static void Main(string[] args)
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(new Form1());
    }
}


Form1側は下記のとおり編集します。

private void Form1_Load(object sender, EventArgs e)
{
    string[] Commands = System.Environment.GetCommandLineArgs();
}

これでCommands配列に引数が格納されます。
[0]の要素に実行ファイル名、[1]以降の要素にコマンドライン引数が格納されます。


実際に実行したとすると

>testApp.exe /a /b /c

Commands[0] = testApp.exe
Commands[1] = /a
Commands[2] = /b
Commands[3] = /c

となります。