Click here to Skip to main content
Licence CPOL
First Posted 15 Jan 2007
Views 20,996
Bookmarked 24 times

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

By | 15 Jan 2007 | Article
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.

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:

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:

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:

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:

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:

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:

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:

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)

About the Author

felixLindemann



Germany Germany

Member



Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
GeneralThe bad thing ... PinmemberJunner20061:06 8 May '08  
GeneralSections PinmembermattieA0:16 23 Jan '07  
GeneralNot another one PinmvpMark Nischalke10:01 15 Jan '07  
GeneralRe: Not another one PinmemberfelixLindemann11:17 15 Jan '07  
GeneralRe: Not another one PinmvpMark Nischalke11:49 15 Jan '07  
GeneralRe: Not another one -> Hey, everybody, look at me! Pinmembercodevigilante8:56 12 Feb '08  
GeneralRe: Not another one -> Hey, everybody, look at me! PinmemberMark Nischalke9:07 12 Feb '08  
GeneralRe: Not another one -> Hey, everybody, look at me! Pinmembercodevigilante3:26 13 Feb '08  
GeneralRe: Not another one -> Hey, everybody, look at me! PinmemberMark Nischalke3:47 13 Feb '08  

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

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

Permalink | Advertise | Privacy | Mobile
Web04 | 2.5.120517.1 | Last Updated 15 Jan 2007
Article Copyright 2007 by felixLindemann
Everything else Copyright © CodeProject, 1999-2012
Terms of Use
Layout: fixed | fluid