Read and Write INI Files Class Sample – VB2005 / VB2008

February 6th, 2009 | Categories: VB | Tags:

Read and Write INI Files Class Sample – VB2005 / VB2008

Below you will find a tiny but yet powerful code to read and write ini files with VB2005 / VB2008 and compatible. The code is written as a class, so, add a Class to your project and use it as is – no changes are required:

Public Class INIClass

    Private Declare Function GetPrivateProfileSection Lib "kernel32" Alias "GetPrivateProfileSectionA" (ByVal lpAppName As String, ByVal lpReturnedString As String, ByVal nSize As Integer, ByVal lpFileName As String) As Integer
    Private Declare Function GetPrivateProfileString Lib "kernel32" Alias "GetPrivateProfileStringA" (ByVal lpApplicationName As String, ByVal lpKeyName As String, ByVal lpDefault As String, ByVal lpReturnedString As String, ByVal nSize As Integer, ByVal lpFileName As String) As Integer
    Private Declare Function WritePrivateProfileSection Lib "kernel32" Alias "WritePrivateProfileSectionA" (ByVal lpAppName As String, ByVal lpString As String, ByVal lpFileName As String) As Integer
    Private Declare Function WritePrivateProfileString Lib "kernel32" Alias "WritePrivateProfileStringA" (ByVal lpApplicationName As String, ByVal lpKeyName As String, ByVal lpString As String, ByVal lpFileName As String) As Integer

    'reads ini string
    Public Shared Function ReadIni(ByVal Filename As String, ByVal Section As String, ByVal Key As String) As String
        Dim RetVal As String, v As Integer
        RetVal = " ".PadRight(255, " ")
        v = GetPrivateProfileString(Section, Key, "", RetVal, RetVal.Length, Filename)
        ReadIni = Left(RetVal, v)
    End Function

    'reads ini section
    Public Shared Function ReadIniSection(ByVal Filename As String, ByVal Section As String) As String
        Dim RetVal As String, v As Integer
        RetVal = " ".PadRight(255, " ")
        v = GetPrivateProfileSection(Section, RetVal, RetVal.Length, Filename)
        ReadIniSection = Left(RetVal, v)
    End Function

    'writes ini
    Public Shared Sub WriteIni(ByVal Filename As String, ByVal Section As String, ByVal Key As String, ByVal Value As String)
        WritePrivateProfileString(Section, Key, Value, Filename)
    End Sub

    'writes ini section
    Public Shared Sub WriteIniSection(ByVal Filename As String, ByVal Section As String, ByVal Value As String)
        WritePrivateProfileSection(Section, Value, Filename)
    End Sub

End Class
No comments yet.