PARSING COMMAND LINE IN VB.NET AND C#
 

Class TCommandLineParser lets developer configure a syntax of command line. VB.NET TCommandLineParser class is almost full clone of the same C++ class (see PARSING COMMAND LINE IN C++). Command line syntax is defined using parameters - building blocks of command line.

Type of command line parameter
Comment
Void Parameter It is valueless parameter. Sometimes it is called "switch". For example, parameters /help and /debug are examples of void parameter.
Integer Parameter

Used to hold integer value.
/timeout=10 is example of integer parameter which value is integer number 10. There are also two special versions of integer parameter:
- positive integer parameter (accepts only positive integers: 1,2,3,....)
- bounded integer parameter (accepts integers from some range).

String Parameter Used to hold strings. If string contains spaces it must be quoted. for example, /dir="\Program files\"
Command Line Configuration Methods Comment
AddVoid(byval name as String) Declares void parameter (switch). For example, AddVoid("help")
AddInt(ByVal name As String, Optional ByVal amust As Boolean = False) Declares integer parameter. When amust=True parameter is mandatory.
For example, call AddInt("timeout") declares optional integer parameter "timeout".
AddIntRep(ByVal name As String, Optional ByVal amust As Boolean = False) Used to declare integer parameter that may present several times in command line.
AddPosInt(ByVal name As String, Optional ByVal amust As Boolean = False) Used to declare positive integer parameter.
AddPosIntRep(ByVal name As String, Optional ByVal amust As Boolean = False) Used to declare positive integer parameter that may present several times in command line.
AddBoundedInt(ByVal name As String, ByVal lwr As Integer, ByVal upr As Integer, Optional ByVal amust As Boolean = False) Used to declare bounded integer parameter.
For example, AddBoundedInt("speed", 0, 260, True) declares mandatory integer parameter "speed" that accepts values from range [0, 260].
AddBoundedIntRep(ByVal name As String, ByVal lwr As Integer, ByVal upr As Integer, Optional ByVal amust As Boolean = False) Used to declare bounded integer parameter that may present several times in command line.
AddString(ByVal name As String, Optional ByVal amust As Boolean = False) Used to declare string parameter.
For example, AddString("host") declares optional string-valued parameter "host".
AddStringRep(ByVal name As String, Optional ByVal amust As Boolean = False) Used to declare string parameter that may present several times in command line.


How to pass real command line arguments to TCommandLineParser object:

Command Line Arguments Methods
Comment
AddItem(ByVal argument As String) Passes one command line argument to object.
For example, AddItem("/timeout=30")
AddItems(ByVal args() As String) Passes command line arguments array to object.

How to access command line parameter values:

Parameter Values Access Methods
Comment
Function FindValue(byval name as String) as Boolean Determines whether argument for parameter was really entered in command line. Use it with optional parameters.
Function GetInt(ByVal name As String, Optional ByVal index As Integer = 0) As Integer Gets integer parameter value. The second optional argument is for number of real command line argument in case of multiple parameter instances. For example,
Dim timeout as Integer = commandline.GetInt("Timeout")
Function GetString(ByVal name As String, Optional ByVal index As Integer = 0) As String Gets string parameter value. For example,
Dim dirname as String = commandline.GetInt("dir")
Function Count(ByVal name As String) As Integer In case parameter may be entered several times in command line Count(name) method gives us exact number of parameter occurences.

How to remove parameter value and parameter from command line:

Clear Methods
Comment
Clear() Removes all parameters declarations from command line object
Clear(ByVal name As String) Removes specified by name parameter from command line object
ClearValue() Clears values for all parameters. All parameters become uninitialized.
ClearValue(ByVal name As String) Unititialize parameter specified by name.


Sample program to demonstrate TCommandLineParser functionality:

 
'
'  Main.vb - TCommandLineParser class functionality test
'
' argument order doesn't matter
' parameter names are case insensitive
' command line argument must follow this rule: /xxxxxx=yyyyyy or /xxxxxx
' where "xxxxxx" is argument (parameter) name and yyyyyy it's value. Argument w/o value 
' we call switch. Please note that there must be no spaces near '=' !!! and parameter name 
' should start with symbol from [a-z_] range.
' these names are valid: "abc", "_k", "_a9" "aa222"
' these names are invalid: "1a", "_12", "5_a", "__"
' Valid command lines (for example below)
'/Void2 /Name1="NAME1 NAME2" /Int1=1 /Int2=2 /arr=1 /arr=2 /VOID1 /positive=1 /bounded1=2 /Bounded1=3
'/Name1="Parameter that contains spaces must be quoted!" /Optional1=blablabla /Int1=666 /arr=1 /positive=1 /bounded1=2 /Bounded1=3 /arr=33
' invalid example (mandatory parameter "Name1" is missing!
'/Int1=666 /arr=1 /positive=1 /bounded1=1
'/name1=abcde /Int1=666 /arr=1 /positive=0 /bounded1=1


Module Main

    ' place to print parameters usage
    Public Sub Usage()
        Console.WriteLine("Usage:")
        ' print here parameters descriptions
        ' ..............
    End Sub


    Sub Main(ByVal args() As String)

        Console.WriteLine("TCommandLineParser illustration")
        Console.WriteLine()
        Try
            ' create command line object
            Dim commandline As New TCommandLineParser
            ' and declare it's syntax
            With commandline
                ' mandatory string-valued parameter "Name1"
                .AddString("Name1", True)
                ' optional string-valued parameter "Optional1"
                .AddString("Optional1")
                ' mandatory integer-valued parameter "Int1"
                .AddInt("Int1", True)
                ' optional integer-valued parameter "Int2"
                .AddInt("Int2")
                ' optional switch "Void1" (switches are always optional!)
                .AddVoid("Void1")
                ' optional switch "Void2"
                .AddVoid("Void2")
                ' optional integer-valued repeatable parameter "Arr"
                .AddIntRep("Arr")
                'optional integer parameter "default"
                .AddInt("default")
                'optional positive integer-valued parameter "positive" (accepts only positive integer values: 1,2,3,...)
                .AddPosInt("positive")
                'optional bounded repeatable integer-valued parameter "bounded2" (accepts onluy values: 1,2,3,4,5)
                .AddBoundedIntRep("bounded1", 1, 5)
                'optional switches
                .AddVoid("help")
                .AddVoid("h")
            End With

            ' feed commandline object with given arguments
            commandline.AddItems(args)

            ' perform validation of command line arguments
            ' really method Validate() will return false only when at least
            ' one mandatory parameter was not initialized (doesn't present in command line)
            If Not commandline.Validate() Then
                Console.WriteLine("Missing some mandatory parameter in command line!")
                Console.ReadLine()
                Return
            End If

            ' if /help or /h was found in command line -> display help and terminate
            If commandline.FindValue("help") Or commandline.FindValue("h") Then
                Usage()
                Return
            End If

            ' the simple way to make parameter default
            ' first, look if parameter "default" really presents in command line
            If Not commandline.FindValue("DEFAULT") Then
                ' if not manually add it supplied with some (default) value
                commandline.AddItem("/default=1")
            End If

            With commandline
                Console.WriteLine("/Name1={0}", .GetString("Name1"))
                ' for optional valued parameters we need first to find them in command line
                If .FindValue("Optional1") Then
                    ' and only after that get its value
                    Console.WriteLine("/Optional1={0}", .GetString("Optional1"))
                End If
                Console.WriteLine("/Int1={0}", .GetInt("Int1"))
                If .FindValue("Int2") Then
                    Console.WriteLine("/Int2={0}", .GetInt("Int2"))
                End If
                If .FindValue("Void1") Then
                    Console.WriteLine("/Void1")
                End If
                If .FindValue("Void2") Then
                    Console.WriteLine("/Void2")
                End If
                If .FindValue("arr") Then
                    ' since "arr" is repeatable parameter - get number of occurences
                    Dim N As Integer = .Count("ARR")
                    Console.WriteLine("Count(""Arr"")={0}", N)
                    For j As Integer = 0 To N - 1
                        Console.WriteLine("/arr={0}", .GetInt("arr", j))
                    Next
                End If

                If .FindValue("positive") Then
                    Console.WriteLine("/positive={0}", .GetInt("positive"))
                End If


                If .FindValue("bounded1") Then
                    Dim N As Integer = .Count("bounded1")
                    Console.WriteLine("Count(""bounded1"")={0}", N)
                    For j As Integer = 0 To N - 1
                        Console.WriteLine("/bounded1={0}", .GetInt("bounded1", j))
                    Next
                    ' now clear values (it seems like this parameter wasn't in command line)
                    .ClearValue("BOUNDED1")
                    ' was it really deleted?
                    If .FindValue("bounded1") Then
                        Console.WriteLine("No, ""bounded1"" is still here")
                    Else
                        Console.WriteLine("Yes, ""bounded1"" has been removed from command line object")
                    End If
                End If

            End With

        Catch ex As Exception
            Console.WriteLine("Exception caught: {0}", ex.Message)
        End Try
        Console.ReadLine()
    End Sub

End Module

Download TCommandLineParser VB.NET code and sample program.
Download TCommandLineParser C# code