Une classe qui fait la lecture et l'écriture dans un fichier ini

Description

une classe qui fait la Lecture et l'écriture dans un fichier INI
  • l'ouverture d'un fichier ini existant.
  • Création d'un fichier ini avec constructeur
  • Ecriture:section,clé,valeur
  • Lecture valeur
  • Vérification si une section ou un clé existe

Source / Exemple :


Public Class ReadWriteINI
    Implements IDisposable

    Private sFichierIni As String
    Private sNomFichierIni As String
    Private sCheminFichierIni As String

    Public Event TextChange()

#Region "Manupilation Macroscopique <Dehors du sFichier ini>"
    Private Function est_ini(ByVal sIni As String)
        Return System.IO.Path.GetExtension(sIni).ToString.ToLower = ".ini"
    End Function
    Private Sub permute_fichiers(ByVal sFichierTmp As String)
        System.IO.File.SetAttributes(sFichierIni, IO.FileAttributes.Normal) 'pour etre supprimer ensuite
        System.IO.File.Delete(sFichierIni)
        System.IO.File.Move(sFichierTmp, sFichierIni)
        System.IO.File.SetAttributes(sFichierIni, IO.FileAttributes.Normal + IO.FileAttributes.ReadOnly)
    End Sub

    Public Sub Changer_ini(ByVal sVal As String, Optional ByVal bSur As Boolean = False)

        If Not System.IO.File.Exists(sVal) Or Not est_ini(sVal) Then
            If est_ini(sVal) Then 'si il n'est pas existant mais ini

                If Not bSur Then 'l'utilisateur n'a pas forcer la création?ile faut lui demander
                    If MsgBox("Voulez vous commême créer un fichier qui comporte ce nom ?" _
                                    , MsgBoxStyle.Exclamation + MsgBoxStyle.YesNo, _
                                    "Ce nom n'est pas existant") <> MsgBoxResult.Yes Then
                        'si l'utilisateur ne veut pas conserver ce nom
                        Me.Dispose()
                        Exit Sub
                    End If
                End If
                Try
                    System.IO.File.Create(sVal)
                    Exit Try
                Catch ex As System.IO.DirectoryNotFoundException
                    System.IO.Directory.CreateDirectory(System.IO.Path.GetDirectoryName(sVal))
                    System.IO.File.Create(sVal)
                    Exit Try
                Catch ex As Exception
                    sVal = String.Empty
                    MsgBox("Verifier que le volume n'est pas on lecture seul ou inixistant", MsgBoxStyle.Critical, "Type d'erreur: " & ex.GetType.ToString)
                End Try

                RaiseEvent TextChange()
            Else 'ni existant ni ini
                MsgBox("Vérifier le nom du fichier et le chemin", MsgBoxStyle.Critical)
                Exit Sub
            End If
        End If
        If String.Compare(Me.sFichierIni, sVal) Then
            Me.sFichierIni = sVal
            RaiseEvent TextChange()
            System.Threading.Thread.Sleep(700)
        End If
    End Sub

#End Region

#Region "Propriétées"
    Public ReadOnly Property IniNom() As String
        Get
            sNomFichierIni = System.IO.Path.GetFileName(sFichierIni)
            Return sNomFichierIni
        End Get
    End Property
    Public ReadOnly Property IniChemin() As String
        Get
            sCheminFichierIni = System.IO.Path.GetDirectoryName(sFichierIni)
            sCheminFichierIni.Trim("\")
            sCheminFichierIni &= "\"
            Return sCheminFichierIni
        End Get
    End Property
    Public ReadOnly Property IniNomTotal() As String
        Get
            Return Me.sFichierIni
        End Get
    End Property
#End Region

#Region "Constructeur"
    Sub New(ByVal sVal As String, Optional ByVal bSur As Boolean = False)
        changer_ini(sVal, bSur)
    End Sub
#End Region

#Region "Destructeur"
    Public Sub Dispose() Implements System.IDisposable.Dispose
        With Me
            .sNomFichierIni = Nothing
            .sFichierIni = Nothing
            .sCheminFichierIni = Nothing
        End With
    End Sub
#End Region

#Region " long signature"

    'Public Function lireIniValeur(ByVal sSection As String, ByVal sCle As String, Optional ByRef iLine As Integer = 0) As String
    '    'elle retourne Nothing si la clé est non trouver
    '    Dim bSection As Boolean = False 'On n'a pas trouver la bonne section
    '    Dim bCle As Boolean = False 'On n'a pas trouver la bonne cle
    '    sSection = sSection.Trim("[", "]") 'enlever les crochets si elles existent
    '    sSection = "[" & sSection & "]" 'Ajouter les crochets

    '    Dim sValeur As String 'variable où on va mètre la valeur du cle

    '    Try

    '        Dim monStreamReader As New System.IO.StreamReader(sFichierIni) 'Stream pour la lecture
    '        Dim sLine As String ' Variable contenant le texte de la sLine
    '        iLine = 0
    '        Do
    '            'REMARQUE:on sore de la boucle si:
    '            '1-on a truver la clé
    '            '2-on a trouver la section est on a pas trouver la clé
    '            '3-Sortie normal: si on a pas trouver la clé

    '            sLine = monStreamReader.ReadLine : iLine += 1

    '            If sLine <> Nothing And Left(sLine, 1) <> ";" And sLine <> "" Then
    '                'les lignes necessaires

    '                If Left(sLine, 1) = "[" And Right(sLine, 1) = "]" Then 'si c'est une section

    '                    If Not bSection Then 'si on a pas trouver la bonne section
    '                        If String.Compare(sLine.ToLower, sSection.ToLower) = 0 Then 'notre section est trouver
    '                            bSection = True
    '                            'la prochaine section on sore
    '                            'la vérification du cle est possible
    '                        End If 'si notre section n'est pas trouver on va à la prochaine ligne
    '                    Else 'la section est déja trouver, la clé?
    '                        'il faut sortir de la procédure
    '                        sValeur = Nothing
    '                        Exit Do
    '                    End If
    '                Else 'si ce n'est pas une section
    '                    If bSection Then 'si on a trouver déja la section désirer
    '                        Dim n As Integer
    '                        n = InStr(1, sLine, "=")
    '                        If n <> 0 Then
    '                            If String.Compare(Left(sLine, n - 1).ToLower, sCle.ToLower) = 0 Then 'si on a trouver la cle
    '                                bCle = True
    '                                sValeur = Right(sLine, sLine.Length - n).ToString
    '                                Exit Do
    '                            End If 'si on a pas trouver la cle on va à la prochaine ligne
    '                        End If
    '                    End If 'Si on a pas trouver déja la section désirer on va à la prochaine ligne
    '                End If
    '            End If
    '        Loop Until sLine Is Nothing

    '        monStreamReader.Close()
    '        'jusqu'à ici tout va bien

    '    Catch ex As Exception
    '        MsgBox("Une erreur Function lireIniValeur", MsgBoxStyle.Critical, "sFichier config.ini...")
    '    End Try

    '    Return sValeur
    'End Function

    'Public Sub ecrireIniValeur(ByVal sSection As String, ByVal sCle As String, ByVal sValeur As String)
    '    'ATTENTION :il faut que l'attribut, du fichier ini, ne soit pas en lecture seul
    '    Dim iValPos As Integer = 0
    '    If lireIniValeur(sSection, sCle, iValPos) <> Nothing Then
    '        Dim sFichierTmp As String = sCheminFichierIni & "tmpconfig.ini"
    '        If System.IO.File.Exists(sFichierTmp) Then System.IO.File.Delete(sFichierTmp)
    '        Try
    '            Dim monstreamReader As New System.IO.StreamReader(sFichierIni) 'Stream pour la lecture
    '            Dim monstreamWriter As New System.IO.StreamWriter(sFichierTmp) 'Stream pour l' ecriture
    '            System.IO.File.SetAttributes(sFichierTmp, IO.FileAttributes.System + IO.FileAttributes.Hidden)
    '            Dim sLine As String ' Variable contenant le texte de la sLine
    '            Dim i As Integer = 0
    '            Do
    '                sLine = monstreamReader.ReadLine : i += 1
    '                If i = iValPos Then
    '                    monstreamWriter.WriteLine(sCle & "=" & sValeur)
    '                Else
    '                    monstreamWriter.WriteLine(sLine)
    '                End If
    '            Loop Until sLine Is Nothing
    '            monstreamReader.Close()
    '            monstreamWriter.Close()
    '            'jusqu'à ici tout va bien
    '            permute_fichiers(sFichierTmp)
    '        Catch ex As Exception
    '            MsgBox("Une erreur Sub ecrireIniValeur.", MsgBoxStyle.Critical, "ouverture du sFichier config.ini")
    '        End Try
    '    End If
    'End Sub
#End Region

#Region "Lecture seul"
    Public Function Lire_cle(ByVal sSection As String, ByVal sCle As String) As String
        Dim ipos As Int16 = 0
        If Me.existe_Cle(sSection, sCle, ipos) Then
            Dim i As Int16 = 0
            Dim sLine As String
            Try
                Dim monstreamreader As New System.IO.StreamReader(Me.IniNomTotal)
                Do
                    sLine = monstreamreader.ReadLine() : i += 1
                    If i = ipos Then
                        Dim svaleur As String
                        Dim n As Int16
                        n = InStr(1, sLine, "=")
                        svaleur = Right(sLine, sLine.Length - n).ToString
                        monstreamreader.Close()
                        Return svaleur
                    End If
                Loop Until sLine = Nothing
                monstreamreader.Close()
            Catch ex As Exception
                MsgBox(ex.GetType.ToString, MsgBoxStyle.Critical, "Function Lire_cle")
            End Try
        End If
    End Function
#End Region

#Region "Controle"
    Private Function existe_Section(ByVal sSection As String, Optional ByRef iLine As Integer = 0) As Boolean
        sSection = sSection.Trim("[", "]") 'enlever les crochets si elles existent
        sSection = "[" & sSection & "]" 'Ajouter les crochets
        Try
            Dim monStreamReader As New System.IO.StreamReader(sFichierIni) 'Stream pour la lecture
            Dim sLine As String ' Variable contenant le texte de la sLine
            Do
                sLine = monStreamReader.ReadLine : iLine += 1
                If Left(sLine, 1) = "[" And Right(sLine, 1) = "]" Then 'si c'est une section
                    If String.Compare(sLine.ToLower, sSection.ToLower) = 0 Then
                        monStreamReader.Close()
                        Return True
                    End If
                End If
            Loop Until sLine Is Nothing
            monStreamReader.Close()
        Catch ex As Exception
            MsgBox("Une erreur Function existe_Section", MsgBoxStyle.Critical, "sFichier config.ini...")
        End Try
        iLine = 0
        Return False
    End Function
    Private Function existe_Cle(ByVal sSection As String, ByVal sCle As String, Optional ByRef iLine As Int16 = 0) As Boolean
        iLine = 0
        If existe_Section(sSection, iLine) Then 'le valeur de iline= pos de sectionsi car elle existe (sinon =0)
            Try
                Dim monStreamReader As New System.IO.StreamReader(Me.sFichierIni)
                Dim sLine As String
                Dim i As Integer = 0
                Do
                    sLine = monStreamReader.ReadLine() : i += 1 'incrementer la ligne de lecture avec i
                    If i > iLine Then 'car iline represente la section elle meme
                        If Left(sLine, 1) = "[" And Right(sLine, 1) = "]" Then Exit Do 'si 2 sections sont succésuves on sore
                        If bcompare(sLine, sCle) Then 'si cette ligne contienne notre clé
                            iLine = i 'on retourne la position
                            monStreamReader.Close() 'je ferme le fichier
                            Return True 'je sore
                        End If
                    End If
                Loop Until sLine = Nothing
                monStreamReader.Close()
            Catch ex As Exception
                MsgBox("Vérifier le code dans <existe_Cle>", MsgBoxStyle.Critical, ex.GetType.ToString)
            End Try
        End If
        Return False 'si je suit ici se qui signefie que j'ai n'est pas trouver le clet donc iline=0
    End Function 'la valeur du diline est soit la position du cle  soit =0 
    Private Function bcompare(ByVal sLine As String, ByVal scle As String) As Boolean
        Dim n As Integer
        n = InStr(1, sLine, "=")
        If n <> 0 Then
            If String.Compare(Left(sLine, n - 1).ToLower, scle.ToLower) = 0 Then 'si on a trouver la cle
                Return True
            End If 'si on a pas trouver la cle on va à la prochaine ligne
        End If
        Return False 'ce n'est pas une ligne qui contien un clé
    End Function

#End Region

#Region "Lecture/Ecriture"

    Private Sub insert_cle(ByVal sCle As String, ByVal ipos As Integer)
        Dim sFichierTmp As String = Me.IniChemin & "tmpconfig.ini"
        If System.IO.File.Exists(sFichierTmp) Then System.IO.File.Delete(sFichierTmp)
        Try
            Dim monstreamReader As New System.IO.StreamReader(sFichierIni) 'Stream pour la lecture
            Dim monstreamWriter As New System.IO.StreamWriter(sFichierTmp) 'Stream pour l' ecriture
            System.IO.File.SetAttributes(sFichierTmp, IO.FileAttributes.System + IO.FileAttributes.Hidden)
            Dim sLine As String
            Dim i As Integer = 0
            Dim deja As Boolean = False
            Do
                sLine = monstreamReader.ReadLine : i += 1
                'si le cle n'existe pas ------------>pos=pos section===>inserer apres la position et avant une autre section
                If i > ipos And ((Left(sLine, 1) = "[" And Right(sLine, 1) = "]") Or sLine = "") And Not deja Then
                    monstreamWriter.WriteLine(sCle & "=")
                    monstreamWriter.WriteLine(sLine)
                    deja = True
                Else
                    monstreamWriter.WriteLine(sLine) '+
                End If
            Loop Until sLine Is Nothing
            monstreamReader.Close()
            monstreamWriter.Close()
            'jusqu'à ici tout va bien
            permute_fichiers(sFichierTmp)

        Catch ex As Exception
            MsgBox("Sub ecrire_cle.si le cle n'existe pas", MsgBoxStyle.Critical, "ouverture du sFichier config.ini")
        End Try
    End Sub
    Private Sub insert_cle(ByVal sCle As String, ByVal ipos As Integer, ByVal sval As String)
        Dim sFichierTmp As String = Me.IniChemin & "tmpconfig.ini"
        If System.IO.File.Exists(sFichierTmp) Then System.IO.File.Delete(sFichierTmp)
        Try
            Dim monstreamReader As New System.IO.StreamReader(sFichierIni) 'Stream pour la lecture
            Dim monstreamWriter As New System.IO.StreamWriter(sFichierTmp) 'Stream pour l' ecriture
            System.IO.File.SetAttributes(sFichierTmp, IO.FileAttributes.System + IO.FileAttributes.Hidden)
            Dim sLine As String
            Dim i As Integer = 0
            Do
                sLine = monstreamReader.ReadLine : i += 1
                'si le cle n'existe pas ------------>pos=pos section===>inserer apres la position et avant une autre section
                If i = ipos Then
                    If bcompare(sLine, sCle) Then monstreamWriter.WriteLine(sCle & "=" & sval)
                Else
                    monstreamWriter.WriteLine(sLine) '+
                End If
            Loop Until sLine Is Nothing
            monstreamReader.Close()
            monstreamWriter.Close()
            'jusqu'à ici tout va bien
            permute_fichiers(sFichierTmp)

        Catch ex As Exception
            MsgBox("Sub ecrire_cle.si le cle n'existe pas", MsgBoxStyle.Critical, "ouverture du sFichier config.ini")
        End Try
    End Sub

    Public Function ecrire_Section(ByVal sSection As String) As Boolean
        
        If existe_Section(sSection) Then
            Return False
        Else
            Dim sFichierTmp As String = Me.IniChemin & "tmpconfig.ini"
            If System.IO.File.Exists(sFichierTmp) Then System.IO.File.Delete(sFichierTmp)
            System.IO.File.SetAttributes(Me.sFichierIni, IO.FileAttributes.Normal)

            sSection = sSection.Trim("[", "]") 'enlever les crochets si elles existent
            sSection = "[" & sSection & "]" 'Ajouter les crochets
            Try
                Dim monstreamReader As New System.IO.StreamReader(sFichierIni) 'Stream pour la lecture
                Dim monstreamWriter As New System.IO.StreamWriter(sFichierTmp) 'Stream pour l' ecriture
                System.IO.File.SetAttributes(sFichierTmp, IO.FileAttributes.System + IO.FileAttributes.Hidden)

                Dim sLine As String

                Do
                    sLine = monstreamReader.ReadLine
                    If sLine = Nothing Then
                        monstreamWriter.WriteLine(sSection)
                    Else
                        monstreamWriter.WriteLine(sLine)
                    End If
                Loop Until sLine = Nothing

                monstreamReader.Close()
                monstreamWriter.Close()
                permute_fichiers(sFichierTmp)
                Return True
            Catch ex As Exception
                MsgBox("Vérifier le code dans <ecrire_Section>", MsgBoxStyle.Critical, ex.GetType.ToString)
            End Try
        End If
    End Function
    Public Function ecrire_cle(ByVal sSection As String, ByVal sCle As String, Optional ByVal sValeur As String = "") As Boolean
        Dim ipos As Int16
        Dim Sectpos As Int16
retry:
        If existe_Section(sSection, ipos) Then 'si la section existe ipos=pos de section
            Sectpos = ipos
            If existe_Cle(sSection, sCle, ipos) Then 'si le cle existe ipos=pos du clé sinon =0

                If sValeur = "" Then
                    Return False 'cad quand je ne met pas valeur<-->je ne veut pas le modifier
                Else 'Cle=NouveauValeur ATTENTION:la position est celle du cle elle tj > pos section
                    insert_cle(sCle, ipos, sValeur) 'ipos ne change pas apres sortie=pos cle
                End If
            Else 'si le cle n'existe pas --> Remember:j'ai la position de section
                insert_cle(sCle, Sectpos) 'ipos ne change pas apres sortie=pos section
            End If
        Else 'la section n'existe pas : creation de la section+cle+valeur par défaut a la fin du fichier
            Select Case MsgBox("Cette section n'existe pas" & vbCrLf & "Risque d'inATTENTION ", _
                        MsgBoxStyle.Exclamation + MsgBoxStyle.AbortRetryIgnore, "Ecriture d'un cle")
                Case MsgBoxResult.Ignore
                    ecrire_Section(sSection)
                    Try
                        Dim monStreamWriter As New System.IO.StreamWriter(Me.sFichierIni, True)
                        monStreamWriter.WriteLine(sCle & "=" & sCle)
                        monStreamWriter.Close()
                        Return True
                    Catch ex As Exception
                        MsgBox("Vérifier le code dans <ecrire_Cle>")
                        Return False
                    End Try
                Case MsgBoxResult.Retry
                    sSection = InputBox("Donner le nom de la section", "Ecriture d'un cle", sSection)
                    sSection = sSection.Trim("[", "]") 'enlever les crochets si elles existent
                    sSection = "[" & sSection & "]" 'Ajouter les crochets
                    GoTo retry
                Case MsgBoxResult.Abort
                    Return False
            End Select
        End If
    End Function

#End Region

End Class

Conclusion :


j'espère que ça va vous aider un peu; en tout cas c'est un essai et c'est ma première application que j'ai faite avec VB.net

Codes Sources

A voir également

Vous n'êtes pas encore membre ?

inscrivez-vous, c'est gratuit et ça prend moins d'une minute !

Les membres obtiennent plus de réponses que les utilisateurs anonymes.

Le fait d'être membre vous permet d'avoir un suivi détaillé de vos demandes et codes sources.

Le fait d'être membre vous permet d'avoir des options supplémentaires.