IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

VBScript Discussion :

WriteIni, besoin d'un coup de main


Sujet :

VBScript

Vue hybride

Message précédent Message précédent   Message suivant Message suivant
  1. #1
    Membre habitué
    Homme Profil pro
    Technicien multi-tâches
    Inscrit en
    Février 2011
    Messages
    7
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Morbihan (Bretagne)

    Informations professionnelles :
    Activité : Technicien multi-tâches
    Secteur : Industrie Pharmaceutique

    Informations forums :
    Inscription : Février 2011
    Messages : 7
    Par défaut WriteIni, besoin d'un coup de main
    Bonjour à tous,

    Voilà quelques jours que je me suis plongé dans un script vbs pour modifier un fichier ini avec ce qu'à saisi l'utilisateur dans une boite de dialogue.

    Je suis presque arrivé au bout, il me reste un petit problème que je n'arrive pas à résoudre.

    La section que je souhaite modifiée est un peu bizarre puisque entre le nom de la section et la première clé il y a une ligne de texte, qui en fait correspond à un sous-menu dans l'interface graphique de l'appli en C qu'on commercialise. Le code que j'utilise écrit la ligne clé=valeur directement en dessous du titre de la section.

    La question est donc : comment retarder l'inscription ou ligne une ligne plus bas ? (j'ai essayé un saut de ligne char(10), qui ne fonctionne pas...)

    Voilà la fonction que j'utilise accompagnée de ReadIni, nécessaire à WriteIni.
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    'Fonction ReadIni
    Function ReadIni( myFilePath, mySection, myKey )
        ' This function returns a value read from an INI file
        '
        ' Arguments:
        ' myFilePath  [string]  the (path and) file name of the INI file
        ' mySection   [string]  the section in the INI file to be searched
        ' myKey       [string]  the key whose value is to be returned
        '
        ' Returns:
        ' the [string] value for the specified key in the specified section
        '
        ' CAVEAT:     Will return a space if key exists but value is blank
        '
        ' Written by Keith Lacelle
        ' Modified by Denis St-Pierre and Rob van der Woude
     
        Const ForReading   = 1
        Const ForWriting   = 2
        Const ForAppending = 8
     
        Dim intEqualPos
        Dim objFSO, objIniFile
        Dim strFilePath, strKey, strLeftString, strLine, strSection
     
        Set objFSO = CreateObject( "Scripting.FileSystemObject" )
     
        ReadIni     = ""
        strFilePath = Trim( myFilePath )
        strSection  = Trim( mySection )
        strKey      = Trim( myKey )
     
        If objFSO.FileExists( strFilePath ) Then
            Set objIniFile = objFSO.OpenTextFile( strFilePath, ForReading, False )
            Do While objIniFile.AtEndOfStream = False
                strLine = Trim( objIniFile.ReadLine )
     
                ' Check if section is found in the current line
                If LCase( strLine ) = "[" & LCase( strSection ) & "]" Then
                    strLine = Trim( objIniFile.ReadLine )
     
                    ' Parse lines until the next section is reached
                    Do While Left( strLine, 1 ) <> "["
                        ' Find position of equal sign in the line
                        intEqualPos = InStr( 1, strLine, "=", 1 )
                        If intEqualPos > 0 Then
                            strLeftString = Trim( Left( strLine, intEqualPos - 1 ) )
                            ' Check if item is found in the current line
                            If LCase( strLeftString ) = LCase( strKey ) Then
                                ReadIni = Trim( Mid( strLine, intEqualPos + 1 ) )
                                ' In case the item exists but value is blank
                                If ReadIni = "" Then
                                    ReadIni = " "
                                End If
                                ' Abort loop when item is found
                                Exit Do
                            End If
                        End If
     
                        ' Abort if the end of the INI file is reached
                        If objIniFile.AtEndOfStream Then Exit Do
     
                        ' Continue with next line
                        strLine = Trim( objIniFile.ReadLine )
                    Loop
                Exit Do
                End If
            Loop
            objIniFile.Close
        Else
            WScript.Echo strFilePath & " doesn't exists. Exiting..."
            Wscript.Quit 1
        End If
    End Function
     
    -------------------------
     
    'Fonction WriteIni
    Sub WriteIni( myFilePath, mySection, myKey, myValue )
        ' This subroutine writes a value to an INI file
        '
        ' Arguments:
        ' myFilePath  [string]  the (path and) file name of the INI file
        ' mySection   [string]  the section in the INI file to be searched
        ' myKey       [string]  the key whose value is to be written
        ' myValue     [string]  the value to be written (myKey will be
        '                       deleted if myValue is <DELETE_THIS_VALUE>)
        '
        ' Returns:
        ' N/A
        '
        ' CAVEAT:     WriteIni function needs ReadIni function to run
        '
        ' Written by Keith Lacelle
        ' Modified by Denis St-Pierre, Johan Pol and Rob van der Woude
     
        Const ForReading   = 1
        Const ForWriting   = 2
        Const ForAppending = 8
     
        Dim blnInSection, blnKeyExists, blnSectionExists, blnWritten
        Dim intEqualPos
        Dim objFSO, objNewIni, objOrgIni, wshShell
        Dim strFilePath, strFolderPath, strKey, strLeftString
        Dim strLine, strSection, strTempDir, strTempFile, strValue
     
        strFilePath = Trim( myFilePath )
        strSection  = Trim( mySection )
        strKey      = Trim( myKey )
        strValue    = Trim( myValue )
     
     
        Set objFSO   = CreateObject( "Scripting.FileSystemObject" )
        Set wshShell = CreateObject( "WScript.Shell" )
     
        strTempDir  = wshShell.ExpandEnvironmentStrings( "%TEMP%" )
        strTempFile = objFSO.BuildPath( strTempDir, objFSO.GetTempName )
     
        Set objOrgIni = objFSO.OpenTextFile( strFilePath, ForReading, True )
        Set objNewIni = objFSO.CreateTextFile( strTempFile, False, False )
     
        blnInSection     = False
        blnSectionExists = False
        ' Check if the specified key already exists
        blnKeyExists     = ( ReadIni( strFilePath, strSection, strKey ) <> "" )
        blnWritten       = False
     
        ' Check if path to INI file exists, quit if not
        strFolderPath = Mid( strFilePath, 1, InStrRev( strFilePath, "\" ) )
        If Not objFSO.FolderExists ( strFolderPath ) Then
            WScript.Echo "Error: WriteIni failed, folder path (" _
                       & strFolderPath & ") to ini file " _
                       & strFilePath & " not found!"
            Set objOrgIni = Nothing
            Set objNewIni = Nothing
            Set objFSO    = Nothing
            WScript.Quit 1
        End If
     
        While objOrgIni.AtEndOfStream = False
            strLine = Trim( objOrgIni.ReadLine )
            If blnWritten = False Then
                If LCase( strLine ) = "[" & LCase( strSection ) & "]" Then
                    blnSectionExists = True
                    blnInSection = True
                ElseIf InStr( strLine, "[" ) = 1 Then
                    blnInSection = False
                End If
            End If
     
            If blnInSection Then
                If blnKeyExists Then
                    intEqualPos = InStr( 1, strLine, "=", vbTextCompare )
                    If intEqualPos > 0 Then
                        strLeftString = Trim( Left( strLine, intEqualPos - 1 ) )
                        If LCase( strLeftString ) = LCase( strKey ) Then
                            ' Only write the key if the value isn't empty
                            ' Modification by Johan Pol
                            If strValue <> "<DELETE_THIS_VALUE>" Then
                                objNewIni.WriteLine strKey & "=" & strValue
                            End If
                            blnWritten   = True
                            blnInSection = False
                        End If
                    End If
                    If Not blnWritten Then
                        objNewIni.WriteLine strLine
                    End If
                Else
                    objNewIni.WriteLine strLine
                        ' Only write the key if the value isn't empty
                        ' Modification by Johan Pol
                        If strValue <> "<DELETE_THIS_VALUE>" Then
                            objNewIni.WriteLine strKey & "=" & strValue
                        End If
                    blnWritten   = True
                    blnInSection = False
                End If
            Else
                objNewIni.WriteLine strLine
            End If
        Wend
     
        If blnSectionExists = False Then ' section doesn't exist
            objNewIni.WriteLine
            objNewIni.WriteLine "[" & strSection & "]"
                ' Only write the key if the value isn't empty
                ' Modification by Johan Pol
                If strValue <> "<DELETE_THIS_VALUE>" Then
                    objNewIni.WriteLine strKey & "=" & strValue
                End If
        End If
     
        objOrgIni.Close
        objNewIni.Close
     
        ' Delete old INI file
        objFSO.DeleteFile strFilePath, True
        ' Rename new INI file
        objFSO.MoveFile strTempFile, strFilePath
     
        Set objOrgIni = Nothing
        Set objNewIni = Nothing
        Set objFSO    = Nothing
        Set wshShell  = Nothing
    End Sub
    J'essaye de comprendre le script ligne par ligne pour trouver l'endroit ou il renvoie la position pour rajouter une ligne plus bas mais j'ai du mal à comprendre comment faire, avec InStr ?

    Merci d'avance aux courageux !!

    EDIT : Je précise que le code est utilisable, les concepteurs ne répondent pas aux questions d'adaptation...
    http://www.robvanderwoude.com/vbstech_files_ini.php

  2. #2
    Membre habitué
    Homme Profil pro
    Technicien multi-tâches
    Inscrit en
    Février 2011
    Messages
    7
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Morbihan (Bretagne)

    Informations professionnelles :
    Activité : Technicien multi-tâches
    Secteur : Industrie Pharmaceutique

    Informations forums :
    Inscription : Février 2011
    Messages : 7
    Par défaut
    Bonjour,

    Petit up, je n'ai toujours pas réussi...

    Mais en même temps j'ai eu une info de développeurs en C qui pensent avoir du mal à faire une mise à jour depuis l'application... donc ça me rassure quant au fait que je galère

    Est-ce que je dois monter les enchères à une bouteille de chouchen et un paquet de gâteaux bretons ?

    Merci à ceux qui me liront !

  3. #3
    Expert confirmé
    Avatar de hackoofr
    Homme Profil pro
    Enseignant
    Inscrit en
    Juin 2009
    Messages
    3 844
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 50
    Localisation : Tunisie

    Informations professionnelles :
    Activité : Enseignant

    Informations forums :
    Inscription : Juin 2009
    Messages : 3 844
    Par défaut

    Vous pouvez voir aussi cette version commentée en français peut-être elle peut vous apporter une autre vision pour votre script

  4. #4
    Expert confirmé
    Avatar de hackoofr
    Homme Profil pro
    Enseignant
    Inscrit en
    Juin 2009
    Messages
    3 844
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 50
    Localisation : Tunisie

    Informations professionnelles :
    Activité : Enseignant

    Informations forums :
    Inscription : Juin 2009
    Messages : 3 844
    Par défaut
    Citation Envoyé par xav990 Voir le message
    La question est donc : comment retarder l'inscription ou ligne une ligne plus bas ? (j'ai essayé un saut de ligne char(10), qui ne fonctionne pas...)

    Pouvez-vous nous fournir plus de détails (càd le contenu fichier.ini en expliquant votre souhait par un exemple concret),car je n'ai pas bien saisi votre question

  5. #5
    Modérateur
    Avatar de l_autodidacte
    Homme Profil pro
    Retraité : Directeur de lycée/Professeur de sciences physiques
    Inscrit en
    Juillet 2009
    Messages
    2 420
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 69
    Localisation : Tunisie

    Informations professionnelles :
    Activité : Retraité : Directeur de lycée/Professeur de sciences physiques
    Secteur : Enseignement

    Informations forums :
    Inscription : Juillet 2009
    Messages : 2 420
    Par défaut
    La question est donc : comment retarder l'inscription ou ligne une ligne plus bas ? (j'ai essayé un saut de ligne char(10), qui ne fonctionne pas...)
    Une explication(formulation de la question) plus détaillée peut nous éclaircir pour pouvoir t'aider.
    Une partie(qui pose problème) du fichier à traiter serait d'un grand secours.
    Ne pas oublier le tag si satisfait.
    Voter pour toute réponse satisfaisante avec pour encourager les intervenants.
    Balises CODE indispensables. Regardez ICI
    Toujours utiliser la clause Option Explicit(VBx, VBS ou VBA) et Ne jamais typer variables et/ou fonctions en VBS.
    Vous pouvez consulter mes contributions
    Ne pas oublier de consulter les différentes FAQs et les Cours/Tutoriels VB6/VBScript
    Ne pas oublier L'Aide VBScript et MSDN VB6 Fr

  6. #6
    Membre habitué
    Homme Profil pro
    Technicien multi-tâches
    Inscrit en
    Février 2011
    Messages
    7
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Morbihan (Bretagne)

    Informations professionnelles :
    Activité : Technicien multi-tâches
    Secteur : Industrie Pharmaceutique

    Informations forums :
    Inscription : Février 2011
    Messages : 7
    Par défaut
    Bonjour,

    Merci pour vos réponses, je reviens un peu tard mais le problème a été résolu directement dans le logiciel en C par les développeurs, pas de prime de fin d'année pour moi !!

    Je passe le sujet en résolu, et vais continuer dans ma branche... Je pense que quelqu'un au boulot a du tomber sur ce topic et a averti la hiérarchie, car ça me parait très étrange qu'une correction soit faite depuis que j'essaye de trouver une solution alors que rien n'a été fait depuis des années...

    Du coup vous pensez bien que je ne peux pas mettre un bout de l'ini, ça va me retomber dessus...

    Merci encore pour votre aide.

    Edit : Et meilleurs voeux à tous !!

+ Répondre à la discussion
Cette discussion est résolue.

Discussions similaires

  1. [webdesign] Je dois reconstituer un frame : besoin d'un coup de main
    Par dom J dans le forum Balisage (X)HTML et validation W3C
    Réponses: 24
    Dernier message: 21/08/2006, 00h24
  2. Besoin d'un coup de main avec print
    Par scaleo dans le forum Langage
    Réponses: 2
    Dernier message: 10/06/2006, 21h12
  3. C++ besoin d'un coup de main
    Par Invité dans le forum C++
    Réponses: 7
    Dernier message: 19/04/2006, 13h28
  4. Problème avec fwrite() : besoin d'un coup de main
    Par yopuke dans le forum Langage
    Réponses: 2
    Dernier message: 16/04/2006, 09h43
  5. besoin d'un coup de main pour une requête ;)
    Par Fabouney dans le forum Requêtes
    Réponses: 3
    Dernier message: 14/11/2005, 23h14

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo