Link to home
Start Free TrialLog in
Avatar of avi9260
avi9260

asked on

Read/Write from/to ini file

Hi All,
I would like to write a vb program for updating ini file.
Sample code is advantage.

Thanks
Avatar of a_pravarakhya
a_pravarakhya

See this code for reading and writing into INI file from VB:

Private 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
Private Declare Function WritePrivateProfileString Lib "kernel32" Alias "WritePrivateProfileStringA" (ByVal lpApplicationName As String, ByVal lpKeyName As Any, ByVal lpString As Any, ByVal lpFileName As String) As Long
Private Sub Form_Load()
    'KPD-Team 1999
    'URL: http://www.allapi.net/
    'E-Mail: KPDTeam@Allapi.net
    Dim Ret As String, NC As Long
    'Write the setting to the file (c:\test.ini) under
    '   Project1 -> Keyname
    WritePrivateProfileString App.Title, "KeyName", "This is the value", "c:\test.ini"
    'Create a buffer
    Ret = String(255, 0)
    'Retrieve the string
    NC = GetPrivateProfileString(App.Title, "KeyName", "Default", Ret, 255, "C:\test.ini")
    'NC is the number of characters copied to the buffer
    If NC <> 0 Then Ret = Left$(Ret, NC)
    'Show our string
    MsgBox Ret
    'Delete the file
    Kill "c:\test.ini"
End Sub

ASKER CERTIFIED SOLUTION
Avatar of vkaushik
vkaushik

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Richie_Simonetti
vkaushik, just a Q:
Why to create those functions where it only changes the name of each one and does the same thing as API plain functions?
You can use the api calls directly also. Its just I had implemented ini file read/write functions this way long time back, so I published that code.
But that is a waste of resources.
Every function call has its punishment, besides, it appears that the code is implemented in a module, so VB has to load entire module in memory to run those functions.
Yes I agree mate. I have said it was long time back. Was just trying to help somebody.
That's fine!, That's fine!
I have to admit that i am very concerned about system resources ;))
Private Declare Function GetPrivateProfileString Lib "KERNEL32" Alias "GetPrivateProfileStringA" (ByVal lpSectionName As String, ByVal lpKeyName As Any, ByVal lpDefault As String, ByVal lpReturnedString As String, ByVal nSize As Long, ByVal lpFileName As String) As Long
Private Declare Function WritePrivateProfileString Lib "KERNEL32" Alias "WritePrivateProfileStringA" (ByVal lpSectionName As String, ByVal lpKeyName As Any, ByVal lpString As Any, ByVal lpFileName As String) As Long

Public Function ProfileSaveItem(lpSectionName As String, lpKeyName As String, lpValue As String, IniFile As String)
' **********************************************************************************
' * PURPOSE: This function saves the passed value to the file                      *
' *          under the section and key names specified                             *
' * PARAMETERS: lpSectionName -> name of the section we want to create (or adjust) *
' *             lpKeyName -> name of the keyname we want to create (or adjust)     *
' *                          in the section given in lpSectionName                 *
' *             lpValue -> The value of the KeyName                                *
' *             IniFile -> Path and name of the ini-file we want to adjust         *
' * RETURN:  No return-value                                                       *
' * REMARK:  - If the ini file does not exist, it is created.                      *
' *          - If the section does not exist, it is created.                       *
' *          - If the key name does not exist, it is created.                      *
' *          - If the key name exists, it's value is replaced.                     *
' **********************************************************************************
On Error GoTo ProfileSaveItemError
    Call WritePrivateProfileString(lpSectionName, lpKeyName, lpValue, IniFile)
    Exit Function
ProfileSaveItemError:
    MsgBox "ProfileSaveItem: " & Err.Number & " " & Err.Description, vbOKOnly + vbCritical
End Function

Public Function ProfileGetItem(lpSectionName As String, _
                               lpKeyName As String, _
                               DefaultValue As String, _
                               IniFile As String, _
                               Optional nWantedValue As Long = 0) As String
' **********************************************************************************
' * PURPOSE: Retrieves a value from an ini file corresponding                      *
' *          to the section and key name passed.                                   *
' * PARAMETERS: lpSectionName -> name of the section we want to create (or adjust) *
' *             lpKeyName -> name of the keyname we want to create (or adjust)     *
' *                          in the section given in lpSectionName                 *
' *             DefaultValue -> if nothing is returned from the ini-file, this     *
' *                             value will be given back to the calling procedure  *
' *             IniFile -> Path and name of the ini-file we want to adjust         *
' *             nWantedValue -> Do we need the full keyvalue or not ?              *
' * RETURN: The return value is the length of the string in ret, including the     *
' *         terminating null. If a default value was passed, and the section or    *
' *         key name are not in the file, that value is returned.                  *
' *         If no default value was passed (""),then success will = 0 if not found.*
' **********************************************************************************
On Error GoTo ProfileGetItemError
    ' Declaration of the variables
    Dim success As Long
    Dim nSize As Long
    Dim ret As String
    Dim nPos As Long
    Dim cTmp As String
    Dim nValue As Long
    ' Pad a string large enough to hold the data.
    ret = Space$(2048)
    nSize = Len(ret)
    success = GetPrivateProfileString(lpSectionName, lpKeyName, DefaultValue, ret, nSize, IniFile)
   
    If success Then
        If nWantedValue = 0 Then
            '//// Full Keyvalue wanted ////
            ProfileGetItem = left$(ret, success)
        Else
            cTmp = left$(ret, success)
            '//// skip preceding keydata ////
            For nValue = 1 To (nWantedValue - 1)
                nPos = InStr(1, cTmp, ",", vbTextCompare)
                If nPos = 0 Then Exit For
                cTmp = Mid(cTmp, nPos + 1)
            Next
            If nValue = nWantedValue Then
                '//// Wanted value is reached ////
                nPos = InStr(1, cTmp, ",", vbTextCompare)
                If nPos <> 0 Then cTmp = Mid(cTmp, 1, nPos - 1)
            Else
                '//// Wanted value is not available ////
                cTmp = ""
            End If
           
            ProfileGetItem = cTmp
        End If
    End If
    Exit Function
ProfileGetItemError:
    MsgBox "ProfileGetItemError: " & Err.Number & " " & Err.Description, vbOKOnly + vbCritical
End Function

Public Function ProfileDeleteItem(lpSectionName As String, lpKeyName As String, IniFile As String)
' **********************************************************************************
' * PURPOSE: This function will remove the keyname and its corresponding value     *
' *          from the section specified in lpSectionName.                          *
' *          This is accomplished by passing vbNullString as the lpValue parameter.*
' * PARAMETERS: lpSectionName -> name of the section we want to create (or adjust) *
' *             lpKeyName -> name of the keyname we want to remove                 *
' *                          in the section given in lpSectionName                 *
' *             IniFile -> Path and name of the ini-file we want to adjust         *
' * RETURN:  No return-value                                                       *
' * EXAMPLE: assuming that an ini file had:                                        *
' *              [Colours]                                                         *
' *              Colour1=Red                                                       *
' *              Colour2=Blue                                                      *
' *              Colour3=Green                                                     *
' *          and this sub was called passing "Colour2" 'as lpKeyName,              *
' *          the resulting ini file would contain:                                 *
' *              [Colours]                                                         *
' *              Colour1=Red                                                       *
' *              Colour3=Green                                                     *
' **********************************************************************************
On Error GoTo ProfileDeleteItemError
    Call WritePrivateProfileString(lpSectionName, lpKeyName, vbNullString, IniFile)
    Exit Function
ProfileDeleteItemError:
    MsgBox "ProfileDeleteItemError: " & Err.Number & " " & Err.Description, vbOKOnly + vbCritical
End Function


Public Function ProfileDeleteSection(lpSectionName As String, IniFile As String)
' **********************************************************************************
' * PURPOSE: This function will remove the entire section corresponding to         *
' *          lpSectionName.This is accomplished by passing vbNullString as both    *
' *          the lpKeyName and lpValue parameters                                  *
' * PARAMETERS: lpSectionName -> name of the section we want to remove             *
' *             IniFile -> Path and name of the ini-file we want to adjust         *
' * RETURN:  No return-value                                                       *
' * EXAMPLE: assuming that an ini file had:                                        *
' *              [Colours]                                                         *
' *              Colour1=Red                                                       *
' *              Colour2=Blue                                                      *
' *              Colour3=Green                                                     *
' *          and this sub was called passing "Colours" as lpSectionName,           *
' *          the resulting Colours section in the ini file would be deleted        *
' **********************************************************************************
On Error GoTo ProfileDeleteSectionError
    Call WritePrivateProfileString(lpSectionName, vbNullString, vbNullString, IniFile)
    Exit Function
ProfileDeleteSectionError:
    MsgBox "ProfileDeleteSectionError: " & Err.Number & " " & Err.Description, vbOKOnly + vbCritical
End Function
Thanks Dhaest,
your comment really helped me in one of my assignments,
Cheers !
Abeetha
To abeetha: No problem. That's why we're here. To solve problems...