Click here to Skip to main content
15,885,881 members
Articles / Programming Languages / Visual Basic

A .NET Class for Creating/Reading/Editing INI Files

Rate me:
Please Sign up or sign in to vote.
2.26/5 (5 votes)
15 Jan 2007CPOL1 min read 46.6K   26   11
Handling INI files in VB.NET.

Introduction

I had always had trouble reading INI files. I didn't want to use APIs. So I just wrote these lines of code in.

How to use the code

Having created a new class, you first set the file name. If no INI file has been created yet, you can add a header text and as many keys and values you like.

VB
Dim myIniFile As New IniFile
With myIniFile
    .Filename = "c:\MyIniFile.ini"  'or any other file
    If .OpenIniFile() Then
        Dim MyValue As String = .GetValue("MyKey")
        .SetValue("Last Use of Application", Date.Now.ToLongDateString)
        If Not .SaveIni Then
            MessageBox.Show("Trouble by writing Ini-File")
        End If
    Else
        MessageBox.Show("No Ini-File found")
    End If

The class itself

The idea was to use a DataTable and a DataSet. So it was not necessary to use arrays. Here is the code:

VB
Imports System.IO
Imports System.Math
Imports System.Security
Imports System.Security.Cryptography
Imports System.Text

  Public Class IniFile

        Private _strFileName As String
        Private _strIniArgumentsBegins As String = "[Arguments]"
        Private _strPrefix As String
        Private _dt As DataTable
        Private _ds As DataSet
        Private _dv As DataView
        Private _dr As DataRow
        Private TmpStringInhaltKomplett As New StringBuilder
        Private StringIniFile As String


    
        Public Property Filename() As String
            Get
                Return _strFileName
            End Get
            Set(ByVal Value As String)
                _strFileName = Value
            End Set
        End Property
        Public Property Prefix() As String
            Get
                Return _strPrefix
            End Get
            Set(ByVal Value As String)
                _strPrefix = Value
            End Set
        End Property

Now, initialise the components:

VB
Public Sub New()
    _ds = New DataSet
    _dt = New DataTable
    _dv = New DataView

    _dt.Columns.Add("Key")
    _dt.Columns.Add("Value")

    _ds.Tables.Add(_dt)
    _dv.Table = _ds.Tables(0)
End Sub

The OpenIniFile() function reads every line of the INI file. After the argument value strIniArgumentsBegins the keys and values list begins. Every new key and its value is added to the dataset. And after everything, the changes are accepted:

VB
Public Function OpenIniFile() As Boolean
Try
    Dim tmpStringLine As String
    Dim tmpStringArguments() As String
    Dim tmpBool As Boolean = False
    If Not File.Exists(Filename) Then
        Return False
    End If
    Dim ssr As StreamReader = New StreamReader(Filename)
    _ds = New DataSet
    _dt = New DataTable
    _dv = New DataView
    _dt.Columns.Add("Key")
    _dt.Columns.Add("Value")

    _ds.Tables.Add(_dt)
    _dv.Table = _ds.Tables(0)
    Do
        tmpStringLine = ssr.ReadLine()
        If tmpStringLine Is Nothing Then Exit Do
        If tmpBool Then
            Try
                tmpStringArguments = tmpStringLine.Split("=")
                _dr = _ds.Tables(0).NewRow
                _dr("Key") = tmpStringArguments(0)
                _dr("Value") = tmpStringArguments(1)
                _ds.Tables(0).Rows.Add(_dr)
            Catch ex As Exception

            End Try
        End If
        If tmpStringLine.StartsWith(_strIniArgumentsBegins) Then
            tmpBool = True
            _strPrefix = TmpStringInhaltKomplett.ToString
        End If
        TmpStringInhaltKomplett.Append(tmpStringLine & Environment.NewLine)
        Loop Until tmpStringLine Is Nothing
        ssr.Close()
        StringIniFile = TmpStringInhaltKomplett.ToString
        Return True
        _ds.AcceptChanges()
    Catch ex As Exception
        Return False
    End Try
End Function

The values in GetValue will be read from a DataView:

VB
Public Function GetValue(ByVal Key As String) As String
    _dv.RowFilter = "Key = '" & Key & "'"
    If _dv.Count > 0 Then
        Return _dv.Item(0).Item("Value")
    Else
        Return "NOTHING"
    End If
End Function

To set values in SetValue, the DataView checks if the key has to be added or changed:

VB
Public Function SetValue(ByVal Key As String, ByVal Value As String) As Boolean
    _dv.RowFilter = "Key = '" & Key & "'"
    If _dv.Count > 0 Then
        _dv.Item(0).Item("Value") = Value
        Console.WriteLine("Änderung am Key '{0}'", Key)
    Else
        _dr = _ds.Tables(0).NewRow
        _dr("Key") = Key
        _dr("Value") = Value
        _ds.Tables(0).Rows.Add(_dr)
        Console.WriteLine("Neuer Eintrag: Key ='{0}' & Value = {1}", Key, Value)
    End If
End Function

In the last step, changes have to be saved. Here, it will be checked if there are any changes and if the file already exists:

VB
Public Function SaveIni() As Boolean
    If Not IsNothing(_ds.GetChanges) Then
        SetValue("_LastSaveOfIniFile", Date.Now.ToLongDateString)
        Try
            _dv.RowFilter = ""
            _dv.Sort = "KEY ASC"
            Dim StringIni As New StringBuilder
            StringIni.Append(_strPrefix & Environment.NewLine)
            StringIni.Append(_strIniArgumentsBegins & Environment.NewLine)
            Dim i As Integer
            For i = 0 To _dv.Count - 1
                StringIni.Append(_dv.Item(i).Item("Key") & "=" & _
                                 _dv.Item(i).Item("Value") & Environment.NewLine)
            Next
            If File.Exists(_strFileName) Then File.Delete(_strFileName)
            Dim ssw As New StreamWriter(_strFileName)
            ssw.WriteLine(StringIni.ToString)
            ssw.Close()
            _ds.AcceptChanges()
            Return True
        Catch ex As Exception
            Return False
        End Try
    Else
        Return True
    End If
End Function

At last, the class must end:

VB
End Class

Review

Following the principle "KISS" --> Keep It Stupid and Simple, a new class is born, to assist you comfortably in editing INI files.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Germany Germany
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralMy vote of 5 Pin
Zisis Stylianos1-Sep-13 5:24
Zisis Stylianos1-Sep-13 5:24 
QuestionPerfect Pin
Zisis Stylianos1-Sep-13 5:12
Zisis Stylianos1-Sep-13 5:12 
GeneralThe bad thing ... Pin
Tumultus8-May-08 1:06
Tumultus8-May-08 1:06 
GeneralSections Pin
mattieA23-Jan-07 0:16
mattieA23-Jan-07 0:16 
GeneralNot another one Pin
Not Active15-Jan-07 10:01
mentorNot Active15-Jan-07 10:01 
GeneralRe: Not another one Pin
felixLindemann15-Jan-07 11:17
felixLindemann15-Jan-07 11:17 
GeneralRe: Not another one Pin
Not Active15-Jan-07 11:49
mentorNot Active15-Jan-07 11:49 
GeneralRe: Not another one -> Hey, everybody, look at me! Pin
codevigilante12-Feb-08 8:56
codevigilante12-Feb-08 8:56 
GeneralRe: Not another one -> Hey, everybody, look at me! Pin
Not Active12-Feb-08 9:07
mentorNot Active12-Feb-08 9:07 
GeneralRe: Not another one -> Hey, everybody, look at me! Pin
codevigilante13-Feb-08 3:26
codevigilante13-Feb-08 3:26 
GeneralRe: Not another one -> Hey, everybody, look at me! Pin
Not Active13-Feb-08 3:47
mentorNot Active13-Feb-08 3:47 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.