Adam Caudill

Security Leader, Researcher, Developer, Writer, & Photographer

Simple INI API

This post was imported from an old blog archive, and predates the creation of AdamCaudill.com.

While storing settings in a INI file is no longer in vogue, so developers (including myself) still find value in this old method of save a program’s settings. The advantages of using INI files instead of the system registry may be numerous, one of the main reasons I use it is portability, by saving a single file I can move the entire settings for my program to any other computer.

My games also use INI files instead of using the registry, this allows them to perform their own user management instead of allow Windows to define how to handle it.

Option Explicit

Declare Function GetPrivateProfileString Lib "kernel32" Alias "GetPrivateProfileStringA" ( _
    ByVal lpApplicationName As String, _
    ByVal lpKeyName As Any, _
    ByVal lpDefault As String, _
    ByVal lpReturnedString As String, _
    ByVal nSize As Long, _
    ByVal lpFileName As String _
    ) As Long

Declare Function WritePrivateProfileString Lib "kernel32" Alias "WritePrivateProfileStringA" ( _
    ByVal AppName As String, _
    ByVal KeyName As String, _
    ByVal keydefault As String, _
    ByVal FileName As String _
    ) As Long

Function INIGetKeyVal(ByVal strFileName As String, ByVal strSection As String, ByVal strKey As String) As String
Dim strRetData As String
Dim lngRetVal As Long

    If Dir$(strFileName) <> "" Then
        strRetData = String$(255, 0)
        lngRetVal = GetPrivateProfileString(strSection, strKey, "", strRetData, Len(RetVal), strFileName)
        If lngRetVal > 0 Then
            INIGetKeyVal = Left$(strRetData, InStr(strRetData, Chr$(0)) - 1)
        End If
    End If
End Function

Function INISetKeyVal(ByVal strFileName As String, ByVal strSection As String, ByVal strKey As String, ByVal strValue As String) As Boolean
Dim lngRetVal As Long

    lngRetVal = WritePrivateProfileString(strSection, strKey, strValue, strFileName)
    INISetKeyVal = (lngRetVal <> 0)
End Function

Adam Caudill