Visual Basic 6 function "ini_list_keys"

Go back

Below you'll find the source for the Visual Basic 6 function ini_list_keys.

Attribute VB_Name = "modIniListKeys"
' This function is downloaded from:
' http://www.stefanthoolen.nl/archive/vb6-functions/
' 
' You may freely distribute this file but please leave all comments, including this one, in it.
' 
' @Author Stefan Thoolen <mail@stefanthoolen.nl>

Option Explicit

''
' Returns all keys in an INI-file chapter
' Useful for simple INI-files but chapters and keys must be unique
' @param    string  inidata         The INI contents (could be file_get_contents(filename))
' @param    string  chapter         The chapter name
' @param    array   keys            By reference; will be filled with all keys
' @param    boolean case_sensitive  When false, all chapters and keys are lower case, otherwise case remains
' @return   integer                 The amount of keys
' @author   Stefan Thoolen <mail@stefanthoolen.nl>
Public Function ini_list_keys(ByVal inidata As String, ByVal chapter As String, ByRef keys() As String, Optional ByVal case_sensitive As Boolean = False) As Integer
    Dim line As Variant, cnt As Integer, ret() As String, recording As Boolean
    Dim p() As String
    
    For Each line In Split(inidata, vbLf)
        ' Removes a Cariage Return if exists
        If Right(line, 1) = vbCr Then line = Left(line, Len(line) - 1)
        ' Removes additional whitespace around the line
        line = Trim(line)
        ' Checks if this is a chapter
        If Left(line, 1) = "[" And Right(line, 1) = "]" Then
            ' Turns of recording
            recording = False
            ' Except if we are in the right chapter
            If case_sensitive And Trim(Mid(line, 2, Len(line) - 2)) = chapter Then
                recording = True
            ElseIf Trim(LCase(Mid(line, 2, Len(line) - 2))) = LCase(chapter) Then
                recording = True
            End If
        ElseIf Left(line, 1) <> ";" And line <> "" Then
            ' Key found
            p = Split(line, "=", 2)
            ReDim Preserve ret(0 To cnt)
            If case_sensitive Then
                ret(cnt) = Trim(p(LBound(p)))
            Else
                ret(cnt) = Trim(LCase(p(LBound(p))))
            End If
            cnt = cnt + 1
        End If
    Next
    
    ' Returns the values
    keys = ret
    ini_list_keys = cnt
End Function