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
avi9260Asked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

a_pravarakhyaCommented:
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

0
vkaushikCommented:
Here goes the code. Just paste in a visual basic form and you can read and write from a vb app.

code starts---------------

Option Explicit

'Win APi declarations

Private Declare Function GetPrivateProfileSection Lib "kernel32" Alias "GetPrivateProfileSectionA" (ByVal lpAppName As String, ByVal lpReturnedString As String, ByVal nSize As Long, ByVal lpFileName As String) As Long
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 WritePrivateProfileSection Lib "kernel32" Alias "WritePrivateProfileSectionA" (ByVal lpAppName As String, ByVal lpString As String, 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()



Dim Str As String

Open "c:\Sample.txt" For Output As #1
Close #1

Dim m_File As String
m_File = "C:\Sample.txt"


'write to file
WriteIniSection m_File, "SampleTest1", ""
WriteIniSection m_File, "SampleTest2", "Here shoud be found some text"


WriteIni m_File, "TestSample3", "Ini1", "This is ini file 1"
WriteIni m_File, "TestSample1", "Ini2", "This is ini file 2"


'read from the file
Str = Str & "SampleTest2 section: " & vbTab & ReadIniSection(m_File, "SampleTest2") & vbCrLf
Str = Str & "SampleTest1 section: " & vbTab & ReadIniSection(m_File, "SampleTest1") & vbCrLf
Str = Str & "Ini1 string: " & vbTab & ReadIni(m_File, "TestSample3", "Ini1") & vbCrLf
Str = Str & "Ini2 string: " & vbTab & ReadIni(m_File, "TestSample1", "Ini2") & vbCrLf

End

End Sub

Public Function ReadIni(Filename As String, Section As String, Key As String) As String
Dim RetVal As String * 255, v As Long
v = GetPrivateProfileString(Section, Key, "", RetVal, 255, Filename)
ReadIni = Left(RetVal, v - 1)
End Function

Public Function ReadIniSection(Filename As String, Section As String) As String
Dim RetVal As String * 255, v As Long
v = GetPrivateProfileSection(Section, RetVal, 255, Filename)
End Function

Public Sub WriteIni(Filename As String, Section As String, Key As String, Value As String)
WritePrivateProfileString Section, Key, Value, Filename
End Sub

Public Sub WriteIniSection(Filename As String, Section As String, Value As String)
WritePrivateProfileSection Section, Value, Filename
End Sub



0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Determine the Perfect Price for Your IT Services

Do you wonder if your IT business is truly profitable or if you should raise your prices? Learn how to calculate your overhead burden with our free interactive tool and use it to determine the right price for your IT services. Download your free eBook now!

Richie_SimonettiIT OperationsCommented:
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?
0
vkaushikCommented:
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.
0
Richie_SimonettiIT OperationsCommented:
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.
0
vkaushikCommented:
Yes I agree mate. I have said it was long time back. Was just trying to help somebody.
0
Richie_SimonettiIT OperationsCommented:
That's fine!, That's fine!
I have to admit that i am very concerned about system resources ;))
0
Dirk HaestProject managerCommented:
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
0
abeethaCommented:
Thanks Dhaest,
your comment really helped me in one of my assignments,
Cheers !
Abeetha
0
Dirk HaestProject managerCommented:
To abeetha: No problem. That's why we're here. To solve problems...
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Visual Basic Classic

From novice to tech pro — start learning today.