2012-11-19 88 views
5

我需要将程序的功能添加到通过命令行打开程序时接受多个命名参数。即解析多个命名命令行参数

program.exe /param1=value /param2=value 

然后能够利用这些参数作为程序中的变量。我已经找到了几种方法来完成这件事,但似乎无法弄清楚如何将它们放在一起。

我已经能够通过一个命名的参数,并使用下面的代码恢复它,而我能复制它每一个可能的命名参数,我知道不能做到这一点的方式参访。

Dim inputArgument As String = "/input=" 
    Dim inputName As String = "" 

    For Each s As String In My.Application.CommandLineArgs 
     If s.ToLower.StartsWith(inputArgument) Then 
      inputName = s.Remove(0, inputArgument.Length) 
     End If 
    Next 

或者,我可以用

My.Application.CommandLineArgs 

得到的命令行的多个未命名参数,但是这需要所有的参数以相同的顺序/格式每次进行传递。我需要能够每次传递一个随机子集的参数。

最终,我希望能够做到的是将每个参数和值分开,并将其加载到多维数组中供以后使用。我知道我可以通过在“=”处分隔字符串并剥离“/”来找到一种方法,但由于我对此有点新,所以我想看看是否存在“优先处理”的交易方式有多个命名参数?

回答

6

我的首选处理方法是使用现有的库,例如Command Line Parser Library。 (不过,在默认情况下,它采用了different input format--input=Value代替/input=value左右为主。)

这使您不必自己编写代码,得到了很多的灵活性和鲁棒性,简化了代码的优势。

+0

这正是我一直在寻找。我真的不关心输入格式是干什么用的?我还没有分配任何东西。感谢您的快速帮助。 – scholzr

1

这是一个小功能来做你想做的事情。它允许您将所有参数存储在结构中的名称 - 值对中。

Module Module1 
Private Structure NameCommandLineStuct 
    Dim Name As String 
    Dim Value As String 
End Structure 
Private CommandLineArgs As New List(Of NameCommandLineStuct) 

Sub Main() 
    If ParseCommandLine() Then 
     For Each commandItem As NameCommandLineStuct In CommandLineArgs 
      Select Case commandItem.Name.ToLower 
       Case "one" 
        Console.Write(String.Format("key one is {0}", commandItem.Value)) 
       Case "two" 
        Console.Write(String.Format("key two is {0}", commandItem.Value)) 
      End Select 
     Next 
    End If 
End Sub 
Function ParseCommandLine() As Boolean 
    'step one, Do we have a command line? 
    If String.IsNullOrEmpty(Command) Then 
     'give up if we don't 
     Return False 
    End If 

    'does the command line have at least one named parameter? 
    If Not Command.Contains("/") Then 
     'give up if we don't 
     Return False 
    End If 
    'Split the command line on our slashes. 
    Dim Params As String() = Split(Command, "/") 

    'Iterate through the parameters passed 
    For Each arg As String In Params 
     'only process if the argument is not empty 
     If Not String.IsNullOrEmpty(arg) Then 
      'and contains an equal 
      If arg.Contains("=") Then 

       Dim tmp As NameCommandLineStuct 
       'find the equal sign 
       Dim idx As Integer = arg.IndexOf("=") 
       'if the equal isn't at the end of the string 
       If idx < arg.Length - 1 Then 
        'parse the name value pair 
        tmp.Name = arg.Substring(0, idx).Trim() 
        tmp.Value = arg.Substring(idx + 1).Trim() 
        'add it to the list. 
        CommandLineArgs.Add(tmp) 
       End If 
      End If 
     End If 

    Next 
    Return True 
End Function 
End Module