VB.net程序处理命令行参数的例子

时间:2021-01-02 14:29:21

很多情况下需要支持命令行运行,但是VB中的主函数并没有直接支持命令行参数,获取方法有些特别。

今天用vb.net做了个,记录在这里以备日后查找。VB的处理与此不同,网上查了下,需要使用系统DLL文件中的GetCommandLine函数。

这里这个程序的命令行参数处理并不是很好,并不完善。命令行参数的处理还是比较复杂的。这里主要是看如何获取VB.net程序的命令行参数。

如有高人精通命令行的处理,有什么好思路也请在这里指点下。^_^

Imports System.IO

Module Module1
    Public AppVersion As String = "1.0"

    Private CommandParameters() As String
    Private isIllogreCase As Boolean = False
    Private isSearchSubDir As Boolean = False
    Private logFileName As String = "log.txt"
    Private fileFilter As String = "*.*"
    Private filePath As String = "./"
    Private LogWriter As TextWriter = Console.Out
    Private patternString As String

    Sub Main()
        If Not IsValidCommandLine() Then
            Exit Sub
        End If

        LogWriter.WriteLine("[" & DateTime.Now & "]Start.")
        StartFind()
        LogWriter.WriteLine("[" & DateTime.Now & "]end.")
        CloseLogWriter()
    End Sub

    Sub PrintUsage()
        Console.WriteLine("FindStringInFiles Version : " & AppVersion)
        Console.WriteLine("功能: 在符合条件的文件中查找指定的字符串。")
        Console.WriteLine("用法:")
        Console.WriteLine("FindStringInFiles ""PatternString""" & _
                          "[-I] [-log [filename]] [-P [drive:]path] -S [-f filter]")
        Console.WriteLine("    PatternString    查找的目标字符串,支持正则表达式。")
        Console.WriteLine("    -I               在查找时忽略大小写,不指明则匹配大小写。")
        Console.WriteLine("    -log [filename]  将结果保存在日志文件中,不给出文件名是默认保存在当前目录的log.txt中。")
        Console.WriteLine("                     不给出-log则输出结果到标准输出。")
        Console.WriteLine("    -P [drive:]path  指定起始路径,不指定则从当前目录开始搜索。")
        Console.WriteLine("    -S               是否搜索子目录,默认不搜索子目录。")
        Console.WriteLine("    -f filter        文件过滤条件,例如-f ’config_*.txt‘")
    End Sub

    Function IsValidCommandLine() As Boolean
        CommandParameters = My.Application.CommandLineArgs.ToArray
        If CommandParameters.Length = 0 Then
            PrintUsage()
            Return False
        End If

        InitLogWriter()
        LogWriter.WriteLine("FindStringInFiles Version : " & AppVersion)
        LogWriter.WriteLine("[" & DateTime.Now & "]CommandLine parameters : " & _
                            Microsoft.VisualBasic.Interaction.Command)

        patternString = CommandParameters(0)

        If Not SetPattern() Then
            Return False
        End If

        If Not SetFilePath() Then
            Return False
        End If
        IsSearchSubdirectory()

        If Not SetFileFilter() Then
            Return False
        End If

        Return True
    End Function

    Function SetPattern()
        For Each p In CommandParameters
            If 0 = String.Compare(p, "-I") Then
                isIllogreCase = True
                Exit For
            Else
                isIllogreCase = False
            End If
        Next
        Return True
    End Function

    Function SetFilePath() As Boolean
        Dim index As Integer = 0
        Dim paremCount As Integer = CommandParameters.Length

        While index < paremCount
            If 0 = String.Compare(CommandParameters(index), "-P") Then
                ' 最后一个参数是 -P 没有参数值
                If index = paremCount - 1 Then
                    LogWriter.WriteLine("Miss value for operation '-P'!")
                    Return False
                Else ' 否则-P的下一个参数就是值
                    filePath = CommandParameters(index + 1)
                    Return True
                End If
            End If
            index += 1
        End While

        If index >= paremCount Then
            fileFilter = "*.*"
        End If

        Return True
    End Function

    Sub IsSearchSubdirectory()
        For Each p In CommandParameters
            If 0 = String.Compare(p, "-S") Then
                isSearchSubDir = True
                Exit For
            Else
                isSearchSubDir = False
            End If
        Next
    End Sub

    Function SetFileFilter() As Boolean
        Dim index As Integer = 0
        Dim paremCount As Integer = CommandParameters.Length

        While index < paremCount
            If 0 = String.Compare(CommandParameters(index), "-f") Then
                ' 最后一个参数是 -f 没有参数值
                If index = paremCount - 1 Then
                    LogWriter.WriteLine("Miss value for operation '-f'!")
                    Return False
                Else ' 否则-f的下一个参数就是值
                    fileFilter = CommandParameters(index + 1)
                    Return True
                End If
            End If
            index += 1
        End While

        If index >= paremCount Then
            fileFilter = "*.*"
        End If

        Return True
    End Function

    Sub InitLogWriter()
        Dim index As Integer = 0
        Dim paremCount As Integer = CommandParameters.Length

        While index < paremCount
            If 0 = String.Compare(CommandParameters(index), "-log") Then
                ' 参数 -log 后面带有文件名
                If index < paremCount - 1 Then
                    logFileName = CommandParameters(index + 1)
                End If
                Exit While
            End If
            index += 1
        End While
        ' 没有指定 -log 选项
        If index > paremCount Then
            Return
        End If

        If File.Exists(logFileName) Then
            File.Delete(logFileName)
        End If
        'Create the log file.
        Dim sw As StreamWriter = New StreamWriter(logFileName)
        LogWriter = sw
    End Sub

    Sub CloseLogWriter()
        LogWriter.Close()
    End Sub

    Sub StartFind()
        LogWriter.WriteLine("找啊,找啊,找到一个在这里~")
        LogWriter.WriteLine("敬个礼啊,握握手。把你放在日志里~")
        LogWriter.WriteLine("哇喔,终于找完了 ^_^")
    End Sub

End Module