Introduction
I needed a way to quickly & easily store settings in an INI file. There are tons of classes out there, but most seemed to be overkill for what I was trying to do. So I put this class together. It works well for me. I hope someone else will find it valuable.
Here's my example INI, note the [eof] required at the end:
; web application settings
[email]
emailAdminFrom = "user@domain.com"
someOtherSetting = "some value"
[eof]
Here's the class:
Imports Microsoft.VisualBasic
Imports System.IO
Public Class ini
Public Shared Function read(ByVal iniFile As String, ByVal searchKey As String)
Dim lenSS As Integer = Len(searchKey)
Dim locQ As Integer
Dim newStr As String
Using sr As StreamReader = _
New StreamReader(HttpContext.Current.Server.MapPath(iniFile))
Dim line As String
Do
line = sr.ReadLine()
If Left(line, lenSS) = searchKey Then
locQ = InStr(line, """")
newStr = Mid(line, (locQ + 1), ((Len(line) - locQ) - 1))
Return newStr
line = Nothing
End If
Loop Until line Is Nothing
sr.Close()
End Using
Return "error"
End Function
Public Shared Function write(ByVal iniFile As String, _
ByVal writeKey As String, ByVal writeValue As String)
Dim iniTempFile As String = "/tempsettings_del.ini"
Dim iniTempOrigFile As String = "/tempsettingsorig_del.ini"
Dim lenSS As Integer = Len(writeKey)
Dim boolEof As Boolean
Dim strEof As String = "[eof]"
Dim iniMappedFile As String = _
HttpContext.Current.Server.MapPath(iniFile)
Dim iniMappedTempFile As String = _
HttpContext.Current.Server.MapPath(iniTempFile)
Dim iniMappedTempOrigFile As String = _
HttpContext.Current.Server.MapPath(iniTempOrigFile)
Dim sw As StreamWriter = New StreamWriter(iniMappedTempFile)
Dim strNewValue = writeKey & " = """ & writeValue & """"
Using sr As StreamReader = New StreamReader(iniMappedFile)
Dim line As String
Do
line = sr.ReadLine()
If Left(line, 5) = strEof Then boolEof = True
If Left(line, lenSS) = writeKey Then
sw.WriteLine(strNewValue)
Else
If boolEof = True Then
sw.WriteLine(strEof)
Exit Do
End If
sw.WriteLine(line)
End If
Loop Until line Is Nothing
sr.Close()
End Using
sw.Close()
File.Move(iniMappedFile, iniMappedTempOrigFile)
File.Move(iniMappedTempFile, iniMappedFile)
File.Delete(iniMappedTempOrigFile)
Return ""
End Function
End Class
Here's an example usage to retrieve a value:
Dim iniSettings as string = "/settings.ini"
Dim strKey as string = "emailAdminFrom"
Dim strEmail = ini.read(iniSettings, strKey)
Here's an example usage to write a value:
Dim iniSettings as string = "/settings.ini"
Dim strKey as string = "emailAdminFrom"
Dim strNewValue as string = "newuseremail@domain.com"
ini.write(iniSettings, strKey, strNewValue)