Home > Articles > Programming > Visual Basic

  • Print
  • + Share This
This chapter is from the book

INI Files

INI files (pronounced "any files" by us southerners) are useful for storing program information and user settings. An INI file is basically a text file with a simple structure that allows you to save and retrieve specific pieces of information; its filename extension is .INI, short for initialization. By storing information in an INI file, you can avoid hard-coding values in your program. This way, you can easily change values without recompiling the program. In the following sections, you will look at some possible uses for INI files, and discover what you need to do to use them in a program.

Understanding INI Files

The structure of INI files is simple. INI files can be viewed and edited with Notepad or any other text editor. A sample INI file is shown in Figure 21.7.

Figure 21.7

INI files can be used to store user settings and other information in an organized manner.

The three elements to an INI file are sections, keys, and values. (Microsoft calls a section an application; the reason for this involves the history of INI files, when an application stored its own settings in WIN.INI.) The parts of an INI file are summarized in Table 21.3.

Table 21.3

Parts of an INI File

Element

Description

Section

A name enclosed in brackets ([]) that groups a set of values and keys together.

Key

A unique string. The key is followed by an equal sign (=) and a value. A key needs to be unique only within a specific section.

Value

The actual information of a particular key in the INI file. A section and key together are used to read or write a value.

The order of sections and keys within the file is not important because the section and key names (should) point to only one value. One final note on the structure of an INI file: A semicolon (;) is used to indicate a comment; any keys or values following a semicolon are ignored. For example, look at this INI section:

[Settings]
DBLocation=P:\USERINFO.MDB

;DBLocation=D:\CODE\TEST.MDB

In the preceding section, switching from a local development database to a production database is easy. You can simply "comment out" the line you don't want.

Using INI Files in Visual Basic

One reason INI files are easy to use is that you do not have to worry about creating the file, opening the file, or finding the correct line. Before you can use INI files, however, you have to declare two Windows API functions and write a couple of "wrapper" functions around them. (To learn more about API calls, see Chapter 20, "Accessing the Windows API.") Simply add a new module to your program, and enter the code from Listing 21.3 in the General Declarations section.

TIP

Build a library of useful functions such as these in a separate module (for example, UTILITY.BAS) that can easily be added to multiple projects.

Listing 21.3  Using INI Files in Your Program

 'API DECLARATIONS
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
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
Public Function sGetINI(sINIFile As String, sSection As String, sKey _
                As String, sDefault As String) As String
    Dim sTemp As String * 256
    Dim nLength As Integer
    sTemp = Space$(256)
    nLength = GetPrivateProfileString(sSection, sKey, sDefault, sTemp, _
              255, sINIFile)
    sGetINI = Left$(sTemp, nLength)
End Function
Public Sub writeINI(sINIFile As String, sSection As String, sKey _
           As String, sValue As String)
    Dim n As Integer
    Dim sTemp As String
    sTemp = sValue
    'Replace any CR/LF characters with spaces
    For n = 1 To Len(sValue)
        If Mid$(sValue, n, 1) = vbCr Or Mid$(sValue, n, 1) = vbLf _
        Then Mid$(sValue, n) = " "
    Next n
    n = WritePrivateProfileString(sSection, sKey, sTemp, sINIFile)
End Sub

After the code in Listing 21.3 has been entered, you can now use the function sGetINI and the subroutine writeINI to easily read and write to an INI file. The following example shows how you can retrieve settings from an INI file for use at program startup.

Listing 21.4  Using an INI File for Program Settings

Sub InitProgram()
Dim sINIFile As String
Dim sUserName As String
Dim nCount As Integer
Dim i As Integer
'Store the location of the INI file
sINIFile = App.Path & "\MYAPP.INI"
'Read the user name from the INI file
sUserName = sGetINI(sINIFile, "Settings", "UserName", "?")
If sUsername = "?"  Then
      'No user name was present – ask for it and save for next time
      sUserName = InputBox$("Enter your name please:")
      writeini sINIFile, "Settings","UserName",sUserName
End If
'Fill up combo box list from INI file and select the user's
'last chosen item
nCount = Cint(sGetINI(sINIFile, "Regions", "Count", 0) )
For i = 1 to nCount
cmbRegn.AddItem sGetINI(sINIFile, "Regions", "Region" & i,"?")
Next i
cmbRegn.Text = sGetINI(sINIFile, "Regions", _
               "LastRegion",cmbRegions.List(0))
End Sub

The code in Listing 21.4 first checks the INI file for a username. By providing the default value ?, you know whether the username already exists in the INI file and can prompt for it. The default value is a great feature because it does not matter whether the INI file even exists.

The next part of the code sample reads the number of regions from the INI file, and uses that value to place each region in a combo box. The final statement sets the Text property of the combo box to a value from the INI file, using the first item in the list as a default.

NOTE

Remember that writeINI is a subroutine, so it does not require parentheses.

Driving your program from INI files, as demonstrated in Listing 21.4, allows you to make minor changes to the program quickly and easily without even recompiling it.

  • + Share This
  • 🔖 Save To Your Account