VB6: Separate command line parameters including quoted paths

February 4, 2009

 

This routine provides a simple and efficient way of separating your command line parameters. Parameters are space delimited and could easily be separated using Split(). The problem with this is that quoted paths can also contain spaces and would be incorrectly broken up.

The following routine separates command line parameters and ignores spaces in quoted paths. It returns a string containing a null separated parameter list.

Private Function SplitArgs() As String
   Dim sArgs As String
   Dim sChar As String
   Dim nCount As Long
   Dim bQuotes As Boolean
   For nCount = 1 To Len(Command$)
      sChar = Mid$(Command$, nCount, 1)
      If sChar = Chr$(34) Then
         bQuotes = Not bQuotes
      End If
      If sChar = Chr$(32) Then
         If bQuotes Then
            sArgs = sArgs & sChar
         Else
            sArgs = sArgs & Chr$(0)
         End If
      Else
         sArgs = sArgs & sChar
      End If
   Next
   SplitArgs = sArgs
End Function

You can then easily separate the parameters into array elements with Split():

 sArgv() = Split(SplitArgs(), Chr$(0))
Advertisements