Handling Multiple Command Line Arguments

CodeGuru content and product recommendations are editorially independent. We may make money when you click on links to our partners. Learn More.

Handling multiple command line arguments has always been ugly in VB

especially when some of the arguments are quoted because they

contain spaces and such. For example, if you wanted to write a program

that takes as an argument a filename, you would have to quote the

filename to ensure that a space inside of it does not confuse your

application.

Unfortunately there is no built-in functionality for handling this situation. This is why I wrote two functions: GetParam and GetParamCount

that I use all the time. They both can handle a mix of quoted and unquoted parameters.


public Function GetParam(Count as Integer) as string

    Dim i as Long
    Dim j as Integer
    Dim c as string
    Dim bInside as Boolean
    Dim bQuoted as Boolean

    j = 1
    bInside = false
    bQuoted = false
    GetParam = ""

    for i = 1 to len(Command)

        c = mid$(Command, i, 1)

        If bInside And bQuoted then
            If c = """" then
                j = j + 1
                bInside = false
                bQuoted = false
            End If
        ElseIf bInside And Not bQuoted then
            If c = " " then
                j = j + 1
                bInside = false
                bQuoted = false
            End If
        else
            If c = """" then
                If j > Count then Exit Function
                bInside = true
                bQuoted = true
            ElseIf c <> " " then
                If j > Count then Exit Function
                bInside = true
                bQuoted = false
            End If
        End If

        If bInside And j = Count And c <> """" then _
           GetParam = GetParam & c

    next i

End Function


public Function GetParamCount() as Integer

    Dim i as Long
    Dim c as string
    Dim bInside as Boolean
    Dim bQuoted as Boolean

    GetParamCount = 0
    bInside = false
    bQuoted = false

    for i = 1 to len(Command)

        c = mid$(Command, i, 1)

        If bInside And bQuoted then
            If c = """" then
                GetParamCount = GetParamCount + 1
                bInside = false
                bQuoted = false
            End If
        ElseIf bInside And Not bQuoted then
            If c = " " then
                GetParamCount = GetParamCount + 1
                bInside = false
                bQuoted = false
            End If
        else
            If c = """" then
                bInside = true
                bQuoted = true
            ElseIf c <> " " then
                bInside = true
                bQuoted = false
            End If
        End If

    next i

    If bInside then GetParamCount = GetParamCount + 1

End Function

More by Author

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Must Read