プログラムの後ろに設定した(する)引数の値を取得するサンプルコードをC#とVisual Basicで紹介します。
引数を取得する手段を3種類紹介しています。
Environmentクラスにある、CommandLineとGetCommandLineArgsを使った
C#とVisual Basic(VB)のサンプルコードを紹介します。
using System;
class Program
{
static void Main(string[] args)
{
String cmd;
String[] opts;
cmd = Environment.CommandLine;
opts = Environment.GetCommandLineArgs();
Console.WriteLine("CommandLine: " + cmd);
int i = 0;
foreach(String opt in opts)
{
Console.WriteLine("opts["+ i + "]: " + opt);
i++;
}
}
}
Imports System
Module Program
Sub Main(args As String())
Dim cmd As String
Dim opts As String()
cmd = Environment.CommandLine
opts = Environment.GetCommandLineArgs()
Console.WriteLine("CommandLine: " & cmd)
Dim i As Integer = 0
For Each opt As String In opts
Console.WriteLine("opts[" & i & "]: " & opt)
i += 1
Next
End Sub
End Module
引数に 1 2 3 4 5 を渡し実行した結果となります。
どちらも当然、同じ出力となります。
D:\repos\EnvCmdCS\bin\Release\netcoreapp3.1>EnvCmdCS.exe 1 2 3 4 5 CommandLine: D:\repos\EnvCmdCS\bin\Release\netcoreapp3.1\EnvCmdCS.dll 1 2 3 4 5 opts[0]: D:\repos\EnvCmdCS\bin\Release\netcoreapp3.1\EnvCmdCS.dll opts[1]: 1 opts[2]: 2 opts[3]: 3 opts[4]: 4 opts[5]: 5
D:\repos\EnvCmdVB\bin\Release\netcoreapp3.1>EnvCmdVB.exe 1 2 3 4 5 CommandLine: D:\repos\EnvCmdVB\bin\Release\netcoreapp3.1\EnvCmdVB.dll 1 2 3 4 5 opts[0]: D:\repos\EnvCmdVB\bin\Release\netcoreapp3.1\EnvCmdVB.dll opts[1]: 1 opts[2]: 2 opts[3]: 3 opts[4]: 4 opts[5]: 5
Mainメソッドを見ると、argsが渡されています。
ここに引数が格納されているので、以下のC#, Visual Basicのサンプルコードで表示してみます。
using System;
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Argument count:" + args.Length);
int i = 0;
foreach(String opt in args)
{
Console.WriteLine("opts[" + i + "]: " + opt);
i++;
}
}
}
Imports System
Module Program
Sub Main(args As String())
Console.WriteLine("Argument count:" & args.Length)
Dim i As Integer = 0
For Each opt In args
Console.WriteLine("opts[" & i & "]: " & opt)
i += 1
Next
End Sub
End Module
引数に A B C D を渡し実行した結果となります。
どちらも当然、同じ出力となります。
D:\repos\ArgsCS\bin\Release\netcoreapp3.1>ArgsCS.exe A B C Argument count:3 opts[0]: A opts[1]: B opts[2]: C
D:\repos\ArgsVB\bin\Release\netcoreapp3.1>ArgsVB.exe A B C Argument count:3 opts[0]: A opts[1]: B opts[2]: C
以上、C#, Visual Basic(VB)で引数を取得するサンプルコードの紹介でした。