Solved

Read/Write from/to ini file

Posted on 2003-10-29
11
8,003 Views
Last Modified: 2007-12-19
Hi All,
I would like to write a vb program for updating ini file.
Sample code is advantage.

Thanks
0
Comment
Question by:avi9260
  • 3
  • 3
  • 2
  • +3
11 Comments
 
LVL 3

Expert Comment

by:a_pravarakhya
ID: 9641320
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
 
LVL 9

Expert Comment

by:Dang123
ID: 9641416
0
 
LVL 1

Accepted Solution

by:
vkaushik earned 125 total points
ID: 9641436
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
 
LVL 16

Expert Comment

by:Richie_Simonetti
ID: 9641736
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
 
LVL 1

Expert Comment

by:vkaushik
ID: 9641879
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
6 Surprising Benefits of Threat Intelligence

All sorts of threat intelligence is available on the web. Intelligence you can learn from, and use to anticipate and prepare for future attacks.

 
LVL 16

Expert Comment

by:Richie_Simonetti
ID: 9641945
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
 
LVL 1

Expert Comment

by:vkaushik
ID: 9641985
Yes I agree mate. I have said it was long time back. Was just trying to help somebody.
0
 
LVL 16

Expert Comment

by:Richie_Simonetti
ID: 9642001
That's fine!, That's fine!
I have to admit that i am very concerned about system resources ;))
0
 
LVL 53

Expert Comment

by:Dhaest
ID: 9642082
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
 

Expert Comment

by:abeetha
ID: 10145725
Thanks Dhaest,
your comment really helped me in one of my assignments,
Cheers !
Abeetha
0
 
LVL 53

Expert Comment

by:Dhaest
ID: 10145755
To abeetha: No problem. That's why we're here. To solve problems...
0

Featured Post

Better Security Awareness With Threat Intelligence

See how one of the leading financial services organizations uses Recorded Future as part of a holistic threat intelligence program to promote security awareness and proactively and efficiently identify threats.

Join & Write a Comment

Suggested Solutions

Introduction While answering a recent question (http://www.experts-exchange.com/Q_27402310.html) in the VB classic zone, I wrote some VB code in the (Office) VBA environment, rather than fire up my older PC.  I didn't post completely correct code o…
The debugging module of the VB 6 IDE can be accessed by way of the Debug menu item. That menu item can normally be found in the IDE's main menu line as shown in this picture.   There is also a companion Debug Toolbar that looks like the followin…
As developers, we are not limited to the functions provided by the VBA language. In addition, we can call the functions that are part of the Windows operating system. These functions are part of the Windows API (Application Programming Interface). U…
Get people started with the process of using Access VBA to control Outlook using automation, Microsoft Access can control other applications. An example is the ability to programmatically talk to Microsoft Outlook. Using automation, an Access applic…

746 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now