Practical Web Programming

Tuesday, November 06, 2007

How to Write to an INI File in Visual Basic

INI files are useful when you want to store the latest state of your program.

In my own experience, I use INI files to read and write any information such as the last user who logs in the system and some initialization of my programs that is not possible through databases.

One thing I like about INI files is that you can change the state or behavior of your program without recompiling it. Since INI files are just text file, you edit it using notepad or any word processing softwares.

If you want to know how to read from an INI file, see my how to read from an Ini file post.

This sourcecodes is also written in Visual Basic 6.

'Procedure: WriteSettingToIni
'Language: Visual Basic
'Parameter: Filename As String = the filename and path of the ini file
' Section As String = a section in an ini file
' Key As String = a key in an ini file that contains the value to read
' Value = the value to write
'Purpose: Writes a value to an INI File
'Usage: WriteSettingToIni("c:\test.ini", "User", "Latest", "kabalweg")

Public 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 Sub WriteSettingToIni(ByVal Filename As String, _
ByVal Section As String, _
ByVal Key As String, _
ByVal Value As String)
Call WritePrivateProfileString(Section, Key, Value, Filename)
End Sub


Recent Post