Working with INI files in .NET

From HashVB
Revision as of 21:14, 14 November 2005 by 213.224.111.244 (Talk)

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search
float
 This article is based on Visual Basic.NET. Find other Visual Basic.NET articles.

Even thou they are a very old technology, an *.ini file still has it uses... Here's how you can use them in VB.NET.

 Imports System.IO.Path
 Imports System.Reflection.Assembly
 Imports System.Text
 
 Module ModIniFile
 
 #Region "Declares"
 
     Private Declare Ansi Function WritePrivateProfileString Lib "kernel32.dll" Alias "WritePrivateProfileStringA" (ByVal lpApplicationName As String, ByVal lpKeyName As String, ByVal lpString As String, ByVal lpFileName As String) As Integer
     Private Declare Ansi Function GetPrivateProfileString Lib "kernel32.dll" Alias "GetPrivateProfileStringA" (ByVal lpApplicationName As String, ByVal lpKeyName As String, ByVal lpDefault As String, ByVal lpReturnedString As StringBuilder, ByVal nSize As Integer, ByVal lpFileName As String) As Integer
 
 #End Region
 
 #Region "Methods"
 
     Public Function PutIniFileString(ByVal Section As String, ByVal Key As String, ByVal Value As String, Optional ByVal IniFile As String = "")
 
         Dim Ini As String
 
         Try
             If Len(IniFile) = 0 Then
                 Ini = GetExecutingAssembly.Location()
                 Ini = Left(Ini, Len(Ini) - Len(GetExtension(Ini))) & ".ini"
             Else
                 Ini = IniFile
             End If
             Return (WritePrivateProfileString(Section, Key, Value, Ini) <> 0)
         Catch ex As Exception
             LogError(ex, "Section: " & Section & " Key: " & Key & " Value: " & Value & " IniFile: " & Ini, "ModIniFile", "PutIniFileString")
         End Try
 
     End Function
 
     Public Function GetIniFileString(ByVal Section As String, ByVal Key As String, Optional ByVal DefaultValue As String = "", Optional ByVal IniFile As String = "") As String
 
         Dim Ini As String
         Dim cValue As New StringBuilder(4096)
         Dim nSize As Integer
 
         Try
             If Len(IniFile) = 0 Then
                 Ini = GetExecutingAssembly.Location()
                 Ini = Left(Ini, Len(Ini) - Len(GetExtension(Ini))) & ".ini"
             Else
                 Ini = IniFile
             End If
             nSize = GetPrivateProfileString(Section, Key, DefaultValue, cValue, 4096, Ini)
             Return cValue.ToString()
         Catch ex As Exception
             LogError(ex, "Section: " & Section & " Key: " & Key & " DefaultValue: " & DefaultValue & " IniFile: " & Ini, "ModIniFile", "GetIniFileString")
         End Try
 
     End Function
 
 #End Region
 
 End Module