0

I have .ini file and I need to edit one line of that with user input

##  General configuration attempt:
###
[Settings]
AppId = 1843
;.................................................
UnlockAllDLCs = 1
UbiConnection = 0
IsUserConnected = 1
;.................................................
PlayerName = SoulFlyers
Language = en-US
SaveLocation = %standard%
;.................................................
Email = *****@flyers.com
Password = so*****1234
CdKey = AAAA-BBBB-CCCC-DDDD
AccountId = ********
TicketId = SoulFlye*****Lovers
;.................................................
###
##  Insert the DLC list that you wish to unlock here:
###
[DLC]
; %appid% = %Name%

In this .ini file I need to change the

PlayerName = SoulFlyers

with user input.

I tried with objOutFile.WriteLine and fileStream.WriteLine like this:

    Option Explicit
Const ForAppending = 8
Dim ws,fso,RootFolder,MyFile,firstNameInput,fileStream
Do
    firstNameInput = inputbox("Please enter your name")
Loop Until firstNameInput <> ""

Set Ws = CreateObject("Wscript.Shell")
RootFolder = Ws.ExpandEnvironmentStrings("%USERPROFILE%\Desktop")
MyFile = RootFolder & "\Edit.txt"
Set fso = CreateObject("Scripting.FileSystemObject")
Set fileStream = fso.OpenTextFile(MyFile,ForAppending,True)
fileStream.WriteLine String(50,"*")
fileStream.WriteLine "First name: " & firstNameInput
fileStream.Close
ws.run DblQuote(MyFile)
'*****************************************
Function DblQuote(Str)
    DblQuote = Chr(34) & Str & Chr(34)
End Function
'*****************************************

but it adds lines to .ini files.

How can I solve it?

Thanks.

Tanjim Ahmed Khan
  • 650
  • 1
  • 9
  • 21
Dariush
  • 11
  • 2
  • 1
    If you open a filestream `ForAppending` I'm not really surprised it only appends stuff. You'll have to read the complete file contents into a string, replace the line you need, and then write the whole contents back to the file. There's plenty of examples on how to read and write files with vbscript. – Geert Bellekens May 29 '20 at 07:21
  • @GeertBellekens no i tried that before. – Dariush May 29 '20 at 07:23
  • 1
    What do you mean with I tried that before? In the duplicate target there are 9 answers, all with a slightly different approach for reading and writing files. And I suspect most of these would work in your situation. – Geert Bellekens May 29 '20 at 07:27
  • @GeertBellekens that's my mistake. i'll check , thanks – Dariush May 29 '20 at 07:34

3 Answers3

0

This function WriteReadIni can be used easily for reading and writing from an INI file :

Here is the English Version :

Option Explicit
Dim Title,fso,oFile,PlayerName,NewPlayerName
Title = "Read and Write from INI file"
Set fso = CreateObject("Scripting.FileSystemObject")
Set oFile = fso.GetFile("Settings.ini")

PlayerName = WriteReadIni(oFile,"Settings","PlayerName",Null) 'For reading only
MsgBox "The content of this variable PlayerName read from Settings.ini file is : " & vbCrlf &_
"PlayerName = " & PlayerName, vbInformation,Title
Do
    PlayerName = inputbox("Please enter your name")
Loop Until PlayerName <> ""

NewPlayerName = WriteReadIni(oFile,"Settings","PlayerName",PlayerName) ' Writing the new variable to ini file
NewPlayerName = WriteReadIni(oFile,"Settings","PlayerName",Null) ' Reading the new variable

MsgBox "The New content of this variable PlayerName read from Settings.ini file is : " & vbCrlf &_
"PlayerName = " & NewPlayerName, vbInformation,Title

'-----------------------------------------------------------------------------------------------------------------------
Function WriteReadIni(oFile,section,key,value)
'-----------------------------------------------------------------------------------------------------------------------
' omen999 - mars 2018 v 1.1 - http://omen999.developpez.com/
' writes / reads the <key> of the <section> section of the oFile file object with the value <value> if read: value = Null 
' In writing if the section and / or the key do not exist, they will be created
' In writing returns false if the key / value pair already existed if not true
' In read returns either: the key value, an empty string in the case of an empty key or False if the key does not exist
'-----------------------------------------------------------------------------------------------------------------------
Dim oText,iniText,sectText,newSectText,keyText,reg,regSub
  ' Initialization of regex objects
  ' Can be moved in the main code in case of successive calls
  Set reg = New RegExp
  Set regSub = New RegExp
  reg.MultiLine=True 'simplifie le pattern
  reg.IgnoreCase = True
  regSub.IgnoreCase = True
  Set oText = oFile.OpenAsTextStream(1,0)
  iniText = oText.ReadAll
  oText.Close
  reg.Pattern = "^\[" & section & "\]((.|\n[^\[])+)"
  regSub.Pattern = "\b" & key & " *= *([^;\f\n\r\t\v]*)"
  On Error Resume Next
  If IsNull(value) Then   ' key reading
    WriteReadIni = regSub.Execute(reg.Execute(iniText).Item(0).SubMatches(0)).Item(0).SubMatches(0)
    If Err.Number = 5 then WriteReadIni = False
  Else                                              ' key writing
    sectText = reg.Execute(iniText).Item(0).SubMatches(0)
    If Err.Number = 5 Then ' Unknown section
      iniText = iniText & vbCrLf & "[" & section & "]" & vbCrLf & key & "=" & value
    Else
      newSectText = regSub.Replace(sectText,key & "=" & value)
      If newSectText = sectText Then ' No replacement noted. either the key / value already exists or it is a new key
        If regSub.Test(sectText) Then ' The key / value pair already exists -> Exit Function
          WriteReadIni = False
          Exit Function 
        End If
        If Right(sectText,1) = vbCr Then keyText = key & "=" & value Else keyText = vbCrLf & key & "=" & value
        newSectText = sectText & keyText
      End If
      iniText = reg.Replace(iniText,"[" & section & "]" & newSectText)
    End If
    Set oText = oFile.OpenAsTextStream(2,0)
    oText.Write iniText
    oText.Close
    WriteReadIni = True
  End If
End Function
'-----------------------------------------------------------------------------------------------------------------------
Hackoo
  • 18,337
  • 3
  • 40
  • 70
0

This could be a nice solution for your issue, i found this neat function on a french forum :

NB : I will try to translate the comments as soon as possible in english

Option Explicit
Dim Title,fso,oFile,PlayerName,NewPlayerName
Title = "Read and Write from INI file"
Set fso = CreateObject("Scripting.FileSystemObject")
Set oFile = fso.GetFile("Settings.ini")

PlayerName = WriteReadIni(oFile,"Settings","PlayerName",Null) 'For reading only
MsgBox "The content of this variable PlayerName read from Settings.ini file is : " & vbCrlf &_
"PlayerName = " & PlayerName, vbInformation,Title

NewPlayerName = WriteReadIni(oFile,"Settings","PlayerName","Dariush") ' write the new variable here as example "Dariush"
MsgBox "The New content of this variable PlayerName read from Settings.ini file is : " & vbCrlf &_
"PlayerName = " & PlayerName, vbInformation,Title

Function WriteReadIni(oFile,section,key,value)
' *******************************************************************************************
' omen999 - mars 2018 v 1.1 - http://omen999.developpez.com/
' écrit/lit la clé <key> de section <section> de l'objet fichier oFile avec la valeur <value> si lecture : value = Null 
' en écriture si la section et/ou la clé n'existent pas, elles seront créées
' en écriture renvoie faux si le couple clé/valeur existait déjà sinon vrai
' en lecture renvoie soit : la valeur de clé, une chaine vide en cas de  clé vide ou Faux si la clé n'existe pas
' ********************************************************************************************
Dim oText,iniText,sectText,newSectText,keyText,reg,regSub
  ' 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.MultiLine=True 'simplifie le pattern
  reg.IgnoreCase = True
  regSub.IgnoreCase = True
  Set oText = oFile.OpenAsTextStream(1,0)
  iniText = oText.ReadAll
  oText.Close
  reg.Pattern = "^\[" & section & "\]((.|\n[^\[])+)"
  regSub.Pattern = "\b" & key & " *= *([^;\f\n\r\t\v]*)"
  On Error Resume Next
  If IsNull(value) Then   ' lecture clé
    WriteReadIni = regSub.Execute(reg.Execute(iniText).Item(0).SubMatches(0)).Item(0).SubMatches(0)
    If Err.Number = 5 then WriteReadIni = False
  Else                                              ' écriture clé
    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 ' pas de remplacement constaté. soit le clé/valeur existe déjà soit c'est une nouvelle clé
        If regSub.Test(sectText) Then ' le couple clé/valeur existe déjà -> sortie
          WriteReadIni = False
          Exit Function 
        End If
        If Right(sectText,1) = vbCr Then keyText = key & "=" & value Else keyText = vbCrLf & key & "=" & value
        newSectText = sectText & keyText
      End If
      iniText = reg.Replace(iniText,"[" & section & "]" & newSectText)
    End If
    Set oText = oFile.OpenAsTextStream(2,0)
    oText.Write iniText
    oText.Close
    WriteReadIni = True
  End If
End Function
Hackoo
  • 18,337
  • 3
  • 40
  • 70
  • thanks i found a solution and share that. – Dariush May 29 '20 at 08:29
  • Thanks For your time left for my problem. – Dariush May 29 '20 at 08:36
  • @Dariush You can give a try for the [new english version](https://stackoverflow.com/questions/62080578/how-to-edit-string-in-ini-file-with-user-input-vbscript?answertab=active#tab-top) that i posted above ! – Hackoo May 29 '20 at 09:20
0

thanks from all. i found the solution for my code. first ask from user to enter his name then, run the prgrom

    Dim fso, objOutFile,PlayerName,fileStream,ws,objShell
    Do
     PlayerName = inputbox("Please Enter Your Name")
    Loop Until PlayerName <> ""
    Set fso = CreateObject("Scripting.FileSystemObject")
    Set objOutFile = fso.CreateTextFile("D:\Program Files (x86)\Games\game\user.ini",True)  


objOutFile.WriteLine "##  General configuration attempt:"
objOutFile.WriteLine "###"
objOutFile.WriteLine "[Settings]"
objOutFile.WriteLine "AppId = 1843"
objOutFile.WriteLine ";................................................."
objOutFile.WriteLine "UnlockAllDLCs = 1"
objOutFile.WriteLine "UbiConnection = 0"
objOutFile.WriteLine "IsUserConnected = 1"
objOutFile.WriteLine ";................................................."
objOutFile.WriteLine "PlayerName = " & PlayerName
objOutFile.WriteLine "Language = en-US"
objOutFile.WriteLine "SaveLocation = %standard%"
objOutFile.WriteLine ";................................................."
objOutFile.WriteLine "Email = soul@******m"
objOutFile.WriteLine "Password = so*****rd1234"
objOutFile.WriteLine "CdKey = AAAA-BBB*****D"
objOutFile.WriteLine "AccountId = c******c2c1"
objOutFile.WriteLine "TicketId = SoulFl****vers"
objOutFile.WriteLine ";................................................."
objOutFile.WriteLine "###"
objOutFile.WriteLine "##    Insert the DLC list that you wish to unlock here:"
objOutFile.WriteLine "###"
objOutFile.WriteLine "[DLC]"
objOutFile.WriteLine "; %appid% = %Name%"
Set objShell = WScript.CreateObject( "WScript.Shell" )
objShell.Run("""D:\Program Files (x86)\Games\\game.exe""")
Dariush
  • 11
  • 2