Processing Command Line Arguments Using System Environment

One common task Main() will undertake is to process any incoming command-line arguments. For example, consider the VB command-line compiler, vbc.exe (see Chapter 2). As you recall, we specified various options (such as /target, /out, and so forth) when compiling our code files. The vbc.exe compiler processed these input flags in order to compile the output assembly. When you wish to build a Main() method that can process incoming command-line arguments for your custom applications, you have a few possible ways to do so.

Your first approach is to make use of the shared GetCommandLineArgs() method defined by the System.Environment type. This method returns you an array of String objects. The first item in the array is simply the name of the executable program, while any remaining items in the array represent the command-line arguments themselves. To illustrate, update your current Main() method as follows:

Class Program Shared Sub Main() Console.WriteLine("***** Fun with Main() *****") ' Get command-line args.

Dim args As String() = Environment.GetCommandLineArgs() Dim s As String For Each s In args

Console.WriteLine("Arg: {0}", s) Next End Sub End Class

Assuming you have built your application, if you were to now run your application at the command prompt, you can feed in your arguments in an identical manner as you did when working with vbc.exe (see Figure 3-3).

raw Administrator VisuaE Studio 2005 Command Prompt

C:\MyApp>FunWithMai n.exe /argl /arg2 /arg3

Arg: FunWithMain.exe

Arg: /argl

Arg: /arg2

Arg: /arg3

Figure 3-3. Processing command-line arguments

Of course, it is up to you to determine which command-line arguments your program will respond to and how they must be formatted (such as with a - or / prefix). Here we simply passed in a series of options that were printed to the command prompt. Assume, however, you were creating a new video game and programmed your application to process an option named -godmode. If the user starts your application with the flag, you know the user is in fact a cheater, and you can take an appropriate course of action.

Was this article helpful?

0 0

Post a comment