Home
VB.NET
Main args, Command-Line Arguments
This page was last reviewed on Nov 25, 2023.
Dot Net Perls
Main, args. Often developers may need to run a VB.NET program as a command-line utility. And in this situation, the program usually must accept command-line arguments.
By specifying a string array argument to Main, the program will automatically receive arguments. We can then loop over the array and act upon its elements.
Example. To begin, the Main method is specified as a Sub, as it does not return a value. It is contained in a Module—the name of the module is not important.
Sub
Module
Step 1 The args parameter is a String array, and thus it has a Length property we can test and print.
Array Length
Step 2 We use the For-Each loop to enumerate the elements in the string array. The file name is not included.
For
Step 3 We can use Select Case—or any other VB.NET construct—to test and handle the String elements.
Select Case
Module Module1 Sub Main(args as String()) ' Step 1: print length of array. Console.WriteLine("Args length is: {0}", args.Length) ' Step 2: loop over each argument. For Each arg in args ' Step 3: print argument and use Select Case to match it. Console.WriteLine("Arg is: {0}", arg) Select Case arg Case "test" Console.WriteLine("TEST ARG") Case "test2" Console.WriteLine("TEST2 ARG") Case Else Console.WriteLine("Unknown") End Select Next End Sub End Module
dotnet run test test2 Args length is: 2 Arg is: test TEST ARG Arg is: test2 TEST2 ARG
Nothing array. In my testing, the args array is never Nothing, even when zero arguments are present. However, it may be worth testing it with IsNothing, depending on where the program will run.
Nothing
Even though VB.NET is a good choice for programs with Windows Forms user interfaces, it can be used for console programs. And for simple tasks, console programs are an ideal choice.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Nov 25, 2023 (new).
Home
Changes
© 2007-2024 Sam Allen.