Command Line Arguments in Visual Basic .NET
Command-line arguments are a common way to parameterize execution of programs. For example, dotnet run MyProgram.dll
uses run
and MyProgram.dll
arguments to the dotnet
program.
Imports System
Module CommandLineArguments
Sub Main(args As String())
' Environment.GetCommandLineArgs() provides access to raw command-line
' arguments. Note that the first value in this array
' is the path to the program, and args holds the arguments to the program.
Dim argsWithProg As String() = Environment.GetCommandLineArgs()
Dim argsWithoutProg As String() = args
' You can get individual args with normal indexing.
Dim arg As String = If(args.Length > 2, args(2), String.Empty)
Console.WriteLine(String.Join(" ", argsWithProg))
Console.WriteLine(String.Join(" ", argsWithoutProg))
Console.WriteLine(arg)
End Sub
End Module
To experiment with command-line arguments it’s best to build the program first.
$ dotnet build CommandLineArguments.vb
$ dotnet run --project CommandLineArguments.vbproj a b c d
/path/to/dotnet CommandLineArguments.dll a b c d
a b c d
c
In Visual Basic .NET, we use the args
parameter of the Main
method to access command-line arguments. The Environment.GetCommandLineArgs()
method provides access to all arguments, including the program name.
Unlike in some other languages, in .NET the args
array passed to Main
doesn’t include the program name as the first element. If you need the program name, you can use Environment.GetCommandLineArgs()
or AppDomain.CurrentDomain.FriendlyName
.
Next, we’ll look at more advanced command-line processing with option parsing libraries available in .NET.