[VB6][VB.net]解析 Command Line 命令列參數的技巧

[VB6][VB.net]解析命令列參數的技巧

 

經常會遇到從 Command Line 讀取一些參數到程式的需求,通常用 CommandLineArgs 或是 VisualBasic 的 Command 函式都可以,但在防呆上就要多下點功夫了,因為 User 不見得會完全照你的想法去輸入,像是有個程式的命令列格式為:

exename [/Q] [/GET] [/PUT] [S1=<String 1>] [S2=<String 2]

 

這個例子表明程式只能接受上面五個參數而且需要固定的格式,所以當 User 發生下面這些情形時要有基本對策:

  1. 參數名稱拼錯了,或在需要 “=”時忘了加上等號。(程式要能提示錯誤處)
  2. 要能忽略大小寫。(程式要能容錯)
  3. 忘了用 “/”帶頭 or 慣用 “-”做分隔也要能接受。(程式要能容錯)
  4. 同樣的參數重複出現多次(自動以最後出現的為準)

 

以下是自我感覺良好且常用的手法分享:

  • 這個程式設計為可接受 /get、/put、/s1=[String]、/s2=[String] 四個參數程式碼如下。
  • 這裡用 like 和 split("=")(1) 取回等號右邊的內容是以前在 VB6 常用的手法,不曉得在 VB.net 下是否還有更簡單的寫法.

 

Imports System.Text
Module Module1
    Dim 讀取 As Boolean = False                   '---用 /get 傳回---
    Dim 寫回 As Boolean = False                   '---用 /put 傳回---
    Dim 字串_01 As String = "我是預設字串_01"     '---用 /s1= 傳回---
    Dim 字串_02 As String = "我是預設字串_02"     '---用 /s2= 傳回---
    Sub Main()
        show變數("---處理前---")
        Console.WriteLine(解析命令列() & vbCrLf)
        show變數("---處理後---")
        Console.Write("Press any key...")
        Console.ReadKey()
    End Sub
    Sub show變數(ByVal s As String)
        Dim 結果 As New StringBuilder
        結果.AppendLine(s)
        結果.AppendLine("讀取 = " & 讀取).AppendLine("寫回 = " & 寫回)
        結果.AppendLine("字串_01 = " & 字串_01).AppendLine("字串_02 = " & 字串_02)
        Console.WriteLine(結果.ToString)
    End Sub
    '---解析命令列的函式---
    Function 解析命令列(Optional ByVal 測試字串 As String = "") As String
        解析命令列 = ""
        Dim 訊息 As New StringBuilder
        Dim 命令集 = IIf(測試字串 = "", My.Application.CommandLineArgs, Split(測試字串, " "))
        For Each c0 As String In 命令集
            Dim c1 = Replace(Replace(c0, "-", "/"), "/-", "/")
            Select Case True
                Case c1.ToLower = "/get" : 讀取 = True
                Case c1.ToLower = "/put" : 寫回 = True
                Case c1 Like "/s1=*" : 字串_01 = c1.Split("=")(1)
                Case c1.ToLower Like "/s2=*" : 字串_02 = c1.Split("=")(1)
                Case Else : 訊息.Append("[" & c0 & "]  ")
            End Select
        Next
        If 訊息.ToString <> "" Then Return "不正確的參數:" & vbCrLf & 訊息.ToString & StrDup(2, vbCrLf)
    End Function
End Module

 

  • 效果:
  • image

ku3