Practical Web Programming

Sunday, November 04, 2007

How to Read from 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.

Below is a read to use function that you can use to read from an INI files. It is written in Visual Basic 6.

Procedure: ReadSettingFromIni
Language: Visual Basic 6
Parameter: Filename = the filename and path of the ini file
Section = a section in an ini file
Key = a key in an ini file that contains the value to read
Purpose: Read a value from an ini file through an API
Usage: MsgBox ReadSettingFromIni("c:\test.ini", "User", "Latest")


'-->API Declaration
Public 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


Public Function ReadSettingFromIni(ByVal Filename As String, _
ByVal Section As String, _
ByVal Key As String) As String
Dim ret As String * 255
Dim NC As Long

NC = GetPrivateProfileString(Section, Key, "", ret, 255, Filename)
If NC <> 0 Then ReadSettingFromIni = Left$(ret, NC)
End Function

Enjoy...

2 comments:

strangebeauty said...

hey feeling pretty good to c something of use. I am quiet interested in the topics u blog on. As a budding programmer, i jus hope the informations u provided may prove helpful in some point of my project development.

And yes thanx for the comment in my blog. looking forward to ur further visits to my page :)

Anonymous said...

Hi,

Thanks that you like my blog. I hope you're enjoying reading my post.

Recent Post