Lettura file ini tramite .NET

Nonostante il formato XML si orami molto diffuso e davvero flessibile, il file ini ancora non si è del tutto estinto. Infatti non è raro trovare configurazioni  gestite mediante questo formato soprattutto in ambito industriale.

I Generics introdotti con la versione 2.0 del .NET Framework possono però venirci in aiuto leggere semplicemente un file INI.

Infatti è possibile creare una classe FileIniReader che gestisce le Sections del fine INI tramite una System.Collections.Generic.Dictionary la cui Key sarà una stringa che indentifica il nome della sezione, mentre il Value sarà un’altra System.Collections.Generic.Dictionary per Keys del file ini.

Questo approccio anche se richiede un minimo di codice in più ci svincola dal dover utilizzare l’approccio Platform Invoke (P/Invoke) per richiamare la funzione API GetPrivateProfileString.

Di seguito il codice della classe FileIniReader:

Public Class FileIniReader
    Public Sub New(ByVal filePath As String)
        Me.filePathValue = filePath
    End Sub

    Private filePathValue As String
    Public ReadOnly Property FilePath As String
        Get
            Return Me.filePathValue
        End Get
    End Property

    Private sectionsValue As New System.Collections.Generic.Dictionary(Of String, System.Collections.Generic.Dictionary(Of String, String))
    Public ReadOnly Property Sections As System.Collections.Generic.Dictionary(Of String, System.Collections.Generic.Dictionary(Of String, String))
        Get
            Return Me.sectionsValue
        End Get
    End Property

    Public Sub Load()
        Me.sectionsValue.Clear()

        Using tr As System.IO.TextReader = System.IO.File.OpenText(Me.filePathValue)
            Dim line As String = String.Empty
            Dim currentGroupName As String = String.Empty
            Dim currentKeyName As String = String.Empty

            Do Until line Is Nothing
                line = tr.ReadLine()
                If line = String.Empty Then Continue Do
                If line.StartsWith(“[“) AndAlso line.EndsWith(“]”) Then
                    ‘Aggiunta Sezione
                    currentGroupName = line.Substring(1, line.Length – 2)
                    Me.sectionsValue.Add(currentGroupName,
                        New System.Collections.Generic.Dictionary(Of String, String))
                ElseIf Not line.StartsWith(“;”) Then
                    ‘Aggiunta Key
                    Dim lineSplitted = line.Split(“=”c)
                    currentKeyName = lineSplitted(0)
                    Me.sectionsValue(currentGroupName).Add(currentKeyName, lineSplitted(1))
                End If
            Loop
            tr.Close()
        End Using
    End Sub

End Class

Considerando di avere ad esempio un file ini C:\Test\Sample.ini come quello mostrato in figura:

image

Per leggerne il contento sarà possibile utilizzare il seguente codice:

Try
    Dim iniReader As New FileIniReader(“C:\Test\Sample.ini”)
    iniReader.Load()

    MsgBox(iniReader.Sections(“Section 1”).Item(“Key 2”))
Catch ex As Exception
    MsgBox(“Errore durante lettura file ini.” & ControlChars.NewLine &
           ex.Message)
End Try

image