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
| Set fso = CreateObject("Scripting.FileSystemObject")
Set wshell = CreateObject("WScript.Shell")
Set oFile = fso.GetFile(wshell.SpecialFolders("MyDocuments") & "\test.ini")
rep = WriteIni(oFile,"UserHome","WWW","nouvelle valeur de clé")
Function WriteIni(oFile,section,key,value)
' écrit ou met à jour la clé <key> de section <section> de l'objet fichier oFile avec la valeur <value>
' si la section et/ou la clé n'existent pas elles seront créées
' renvoie toujours vrai
Dim oText,iniText,sectText,newSectText,keyText
' Initialisation des objets regexp
' peut être déplacé dans le code principal en cas d'appels successifs
Set reg = New RegExp
Set regSub = New RegExp
reg.IgnoreCase = True
regSub.IgnoreCase = True
' lecture du fichier ini et fermeture
Set oText = oFile.OpenAsTextStream(1,0)
iniText = oText.ReadAll
oText.Close
'extraction du contenu de la bonne section et remplacement de la valeur
reg.Pattern = "\[" & section & "\]([^\[]+)":regSub.Pattern = "\b" & key & " *= *([^;\f\n\r\t\v]*)"
On Error Resume Next
sectText = reg.Execute(iniText).Item(0).SubMatches(0)
If Err.Number = 5 Then ' section inconnue
iniText = iniText & vbCrLf & "[" & section & "]" & vbCrLf & key & "=" & value
Else
newSectText = regSub.Replace(sectText,key & "=" & value)
If newSectText = sectText Then ' clé inconnue
If Right(sectText,2) = vbCrLf Then keyText = key & "=" & value & vbCrLf Else keyText = vbCrLf & key & "=" & value & vbCrLf
newSectText = sectText & keyText
End If
iniText = reg.Replace(iniText,"[" & section & "]" & newSectText)
End If
' écriture du fichier
Set oText = oFile.OpenAsTextStream(2,0)
oText.Write iniText
oText.Close
WriteIni = True
End Function |
Partager