Skip to content

Parse Command Line Arguments in .Net

Here’s a sweet and simple function that processes the command line arguments of a VB.Net application and returns a HashTable full of key-value pairs.

    ' This code is published under the University of Illinois Open Source License
    ' Author: Edward Delaporte

Private Function GetCommandLineArguments() As Hashtable
    Dim args As Hashtable
    Dim rawArgs As Array
    args = New Hashtable
    rawArgs = Environment.GetCommandLineArgs()
    For Each arg As String In rawArgs
        Dim key As String = ""
        Dim val As String = ""
        If arg.StartsWith("--") Then
            key = arg.Remove(0, 2)
        ElseIf arg.StartsWith("-") Or arg.StartsWith("/") Then
            key = arg.Remove(0, 1)
        End If
        If key <> "" Then
            Dim x As Integer = Array.IndexOf(rawArgs, arg) + 1
            If rawArgs.Length > x Then
                val = rawArgs(x)
            End If
            If val.StartsWith("-") Or val.StartsWith("--") Or val.StartsWith("/") Then
                val = ""
            End If
            key = key.ToLower
            If Not args.Contains(key) Then args.Add(key, val)
        End If
    Next
    Return args
End Function