About   -   Contact   -   Purchase   -   Search   -   What's New

INI File Handling
As an alternative method to standard file handling, using Open...Close #1 etc, we can use a couple of API functions to read and write INI files. The advantage of these functions are in the simplicity of the code involved. Create a form with 4 TextBoxes: txtFile, txtApp, txtKey and txtVal and 2 Command Buttons: cmdRead and cmdWriteAdd the following code to the declarations section of a form:
Option Explicit

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 Long, ByVal lpFileName _
  As String) As Long
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 Long

Next add code behind the command buttons click event to read from and write to the INI files as follows:

Private Sub cmdRead_Click()
'<DESC>		Reads data from INI files</DESC>
'<RETURN>	String read from INI file
  Dim strBuffer As String * 256
  Dim lngLength As Long
  lngLength = GetPrivateProfileString( _
    txtApp.Text, txtKey.Text, "<no value>", _
    strBuffer, Len(strBuffer), txtFile.Text)
  txtVal.Text = Left$(strBuffer, lngLength)

End Sub

Private Sub cmdWrite_Click()
'<DESC>		Writes data to INI files</DESC>
  WritePrivateProfileString _
    txtApp.Text, txtKey.Text, _
    txtVal.Text, txtFile.Text
  txtVal.Text = "Finished"

End Sub
Example INI file:


[Recent Files]

Variable definitions:

txtFile - is the full path & filename of the INI file
txtApp - is the INI subgroup, held in square brackets, eg. [Settings]
txtKey - is the property name, eg. [LastView]
txtVal - is the actual value, eg. 6

If any of the arguments passed in the GetPrivateProfileString function during INI reading are incorrect then the return string is set to <no value>. During INI writing, if the specified INI file does not exist then one is created, otherwise the INI file is appended to or overwritten, depending on whether the subgroups or properties exist or not..

Top of Page

Legal Notice

Ken Howe 2011