ur

Change values in config files

10 posts in this topic

I have a custom configuration file which has key-value pairs as in below format.

BuildLocation:C:\Build
BuildExe:setup.exe
Release:r9.64.02
Silent:No
InstallPath:default
Compare :No
MartUpgrade :Yes
Bit:64
ERwinUpgrade:No

I need to change the value of "BuildExe" using my program.

Is there any inbuilt function already available for these kind of files?.

Can any one help me how to do this.

Share this post


Link to post
Share on other sites



ur,

What code have you tried that has not worked?

M23


Any of my own code posted anywhere on the forum is available for use by others without any restriction of any kind._______My UDFs:

Spoiler

ArrayMultiColSort ---- Sort arrays on multiple columns
ChooseFileFolder ---- Single and multiple selections from specified path treeview listing
Date_Time_Convert -- Easily convert date/time formats, including the language used
ExtMsgBox --------- A highly customisable replacement for MsgBox
GUIExtender -------- Extend and retract multiple sections within a GUI
GUIFrame ---------- Subdivide GUIs into many adjustable frames
GUIListViewEx ------- Insert, delete, move, drag, sort, edit and colour ListView items
GUITreeViewEx ------ Check/clear parent and child checkboxes in a TreeView
Marquee ----------- Scrolling tickertape GUIs
NoFocusLines ------- Remove the dotted focus lines from buttons, sliders, radios and checkboxes
Notify ------------- Small notifications on the edge of the display
Scrollbars ----------Automatically sized scrollbars with a single command
StringSize ---------- Automatically size controls to fit text
Toast -------------- Small GUIs which pop out of the notification area

 

Share this post


Link to post
Share on other sites

Perhaps you can just read and write to it using IniRead and IniWrite (see helpfile). I noticed the file name does not have to end in .ini for these function to work.

It expects = though for the assigns so I am not sure.

 

Share this post


Link to post
Share on other sites
55 minutes ago, aiter said:

Perhaps you can just read and write to it using IniRead and IniWrite (see helpfile). I noticed the file name does not have to end in .ini for these function to work.

It expects = though for the assigns so I am not sure.

 

But in this file there is no sections as in INI files.

And also here we are using : instead of =.

Share this post


Link to post
Share on other sites
2 hours ago, Melba23 said:

ur,

What code have you tried that has not worked?

M23

Hi Melba,

I starting writing logic as reading line by line and doing string compare and split at : in that particular line.

But my colleague told that he saw sometime back direct library for these kind of files in AutoIT.

So, can you suggest anything like that if possible.

Share this post


Link to post
Share on other sites

#6 ·  Posted (edited)

ur,

Alas I have no knowledge of such a library.

I would have suggested reading the file into an array, looking for the element containing "BuildExe:" and replacing it, before rewriting the file.

M23

Edit: When you reply, please use the "Reply to this topic" button at the top of the thread or the "Reply to this topic" editor at the bottom rather than the "Quote" button - responders know what they wrote and it just pads the thread unnecessarily.

 

Edited by Melba23

Any of my own code posted anywhere on the forum is available for use by others without any restriction of any kind._______My UDFs:

Spoiler

ArrayMultiColSort ---- Sort arrays on multiple columns
ChooseFileFolder ---- Single and multiple selections from specified path treeview listing
Date_Time_Convert -- Easily convert date/time formats, including the language used
ExtMsgBox --------- A highly customisable replacement for MsgBox
GUIExtender -------- Extend and retract multiple sections within a GUI
GUIFrame ---------- Subdivide GUIs into many adjustable frames
GUIListViewEx ------- Insert, delete, move, drag, sort, edit and colour ListView items
GUITreeViewEx ------ Check/clear parent and child checkboxes in a TreeView
Marquee ----------- Scrolling tickertape GUIs
NoFocusLines ------- Remove the dotted focus lines from buttons, sliders, radios and checkboxes
Notify ------------- Small notifications on the edge of the display
Scrollbars ----------Automatically sized scrollbars with a single command
StringSize ---------- Automatically size controls to fit text
Toast -------------- Small GUIs which pop out of the notification area

 

Share this post


Link to post
Share on other sites

this is one of the possible solutions:

#include <Array.au3>
#include <File.au3>

Global $aText[1][1]
Global $sConfig = 'MyConfigFile.txt'

_FileReadToArray($sConfig, $aText, $FRTA_COUNT)
_ArrayColInsert($aText, 1)
For $i = 1 To $aText[0][0]
    $aSplit = StringSplit($aText[$i][0], ':')
    $aText[$i][0] = $aSplit[1]
    For $j = 2 To $aSplit[0]
        $aText[$i][1] &= $aSplit[$j]
        If $j < $aSplit[0] Then $aText[$i][1] &= ':'
    Next
Next
;_ArrayDisplay($aText)
_ChangeValueForKey($aText, 'BuildExe', 'NewValue')  ;change NewValue to your needs
;_ArrayDisplay($aText)
_FileWriteFromArray($sConfig,$aText,1,Default,':')

Func _ChangeValueForKey(ByRef $aArray, $sKey, $sValue)
    For $i = 1 To $aArray[0][0]
        If $aArray[$i][0] = $sKey Then
            $aArray[$i][1] = $sValue
            Return
        EndIf
    Next
EndFunc   ;==>_ChangeValueForKey

note: the solution is exactly to your demo data, if real data isn't conform to it, it doesn't work.

Share this post


Link to post
Share on other sites

Here's another way. Uses regex to support multiple different separators for the key and value delimiter.

#include <File.au3>

FileWrite(@ScriptDir & "\Config File.cfg", "BuildLocation:C:\Build" & @CRLF & _
"BuildExe:setup.exe" & @CRLF & _
"Release:r9.64.02" & @CRLF & _
"Silent:No" & @CRLF & _
"InstallPath:default" & @CRLF & _
"Compare :No" & @CRLF & _
"MartUpgrade :Yes" & @CRLF & _
"Bit:64" & @CRLF & _
"ERwinUpgrade:No")

ConfigFileWrite(@ScriptDir & "\Config File.cfg", "BuildExe", "New Builder Program.exe")

ShellExecute(@ScriptDir & "\Config File.cfg")

Func ConfigFileWrite(Const $sFilePath, Const $sConfigKey, Const $sConfigValue, $sRegexPattern = Default)
    Local $aFileData = Null
    Local $sSeperator = Null

    _FileReadToArray($sFilePath, $aFileData, $FRTA_NOCOUNT)

    If (@error) Then Return SetError(@Error, @Extended, 0)

    If ($sRegexPattern = Default) Then
        $sRegexPattern = "([:-])"
    Else
        $sRegexPattern = "([" & $sRegexPattern & "])"
    EndIf

    For $i = 0 to UBound($aFileData) - 1
        Local $aFileLine = StringSplit(StringRegExpReplace($aFileData[$i], $sRegexPattern, "=", 1), "=", $STR_NOCOUNT)
        If (Not IsArray($aFileLine)) Then Return SetError(-1, 0, "")

        If (StringStripWS($aFileLine[0], $STR_STRIPLEADING + $STR_STRIPTRAILING) = $sConfigKey) Then
            $aFileData[$i] = StringReplace($aFileData[$i], StringStripWS($aFileLine[1], $STR_STRIPLEADING + $STR_STRIPTRAILING), $sConfigValue)
            Return _FileWriteFromArray($sFilePath, $aFileData)
        EndIf
    Next

    Return SetError(-2, 0, 0)
EndFunc

 

Share this post


Link to post
Share on other sites

#9 ·  Posted (edited)

simpler example, based on script by AutoBert in post #7:

#include <Array.au3>
#include <File.au3>

Global $aConfig
Global $sConfigFile = 'config.txt'

_FileReadToArray($sConfigFile, $aConfig, $FRTA_NOCOUNT)
_ChangeValueForKey($aConfig, 'BuildExe', 'NewValue')
_FileWriteFromArray($sConfigFile, $aConfig)

Func _ChangeValueForKey(ByRef $aConfig, $sKey, $sValue)
    For $i = 0 To UBound($aConfig) - 1
        If StringLeft($aConfig[$i], StringLen($sKey) + 1) = $sKey & ':' Then
            $aConfig[$i] = $sKey & ':' & $sValue
            Return
        EndIf
    Next
EndFunc   ;==>_ChangeValueForKey

you don't need to split each line by colon (it's also prone to issues as there may be more than one colon in each line - e.g. first line in demo config at first post). all you need to do is check each line, the first one that you see that begins with the key name, you simply rewrite it.

Edited by orbs

Share this post


Link to post
Share on other sites

#10 ·  Posted (edited)

this is the one I came up with.

Func writeConfig($sFilePath,$intStartCode,$sReplaceText)

;$sReplaceText = "sdfdsfdsfsd"
;$sFilePath = "C:\Users\KIRUD01\Desktop\Config.txt"
;$intStartCode = "BuildExe"
$arrRetArray = ""
$s = _FileReadToArray($sFilePath, $arrRetArray);Reading text file and saving it to array $s will show status of reading file..
$intStartingPointFound = 0
    For $i = 1 To UBound($arrRetArray)-1
        $line = $arrRetArray[$i];retrieves taskengine text line by line
        If StringInStr($line, $intStartCode) Then
                $intStartingPointFound = 1;if found the starting point of the module to copy then set this variable to 1
                ConsoleWrite ("Starting point " &  @CRLF)
                $arrRetArray[$i] = $intStartCode & ": " & $sReplaceText
                ExitLoop
        EndIf
        if $i = UBound($arrRetArray)-1 then ConsoleWrite("Not Found" & @CRLF)
    Next
_FileWriteFromArray ($sFilePath, $arrRetArray,1)

EndFunc

 

Edited by ur

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!


Register a new account

Sign in

Already have an account? Sign in here.


Sign In Now

  • Similar Content

    • RC86
      By RC86
      Afternoon, I could very well be doing this wrong so feel free to totally advise otherwise - I'm wanting to use a GUI to first display a key from within an INI file, then secondly change the INI file by using a FileSelectFolder command but then I want to see the GUI change to reflect the change I've just made.
      #include <ButtonConstants.au3> #include <EditConstants.au3> #include <GUIConstantsEx.au3> #include <WindowsConstants.au3> #Region ### START Koda GUI section ### Form= $Form1 = GUICreate("Form1", 615, 437, 192, 124) $Input1 = GUICtrlCreateInput(Iniread(@WorkingDir & "\test.ini","Path","FilePath",""), 64, 80, 121, 21) $Button1 = GUICtrlCreateButton("Change", 200, 80, 75, 25) GUISetState(@SW_SHOW) #EndRegion ### END Koda GUI section ### While 1 $nMsg = GUIGetMsg() Switch $nMsg Case $GUI_EVENT_CLOSE Exit Case $Button1 $selectedFolder = FileSelectFolder("Select Log Path Directory",@WorkingDir,0) If NOT $selectedFolder = "" Then $newLogPath = IniWrite(@WorkingDir & "\test.ini","Path","FilePath",$selectedFolder) EndIf EndSwitch WEnd So 2 part question really: (1) Should I be using GUICtrlCreateInput to display my INI read from within the GUI? (2) How can I refresh the GUI to update that to read the new information I've just written to the GUI?
      Thanks!

    • LWC
      By LWC
      I've made a program that relies on IniReadSectionNames. It reads (~3K) Autorun.inf files in the working folder and creates a GUI based on their contents.
      I made sure to revert to a default GUI upon @error.
      But someone (with Windows XP SP3 32-bit) reported to me he always gets the default menu.
      I sent him a FileRead command instead and it works! So seemingly there's no access problem to AutoRun.inf.
      In the following demo code, I always hit success, but he always ends up with semi-success:
      Local $hIniLocation = "Autorun.inf" Local $aSections = IniReadSectionNames($hIniLocation) If @error Then $aSections = FileRead($hIniLocation) if @error then msgbox(48, "Double error", "Alternative access failed too due to:" & @crlf & @error & @crlf & @extended) else msgbox(0, "Semi-success", "IniReadSectionNames failed, but alternativaly this file contains:" & @crlf & @crlf & $aSections) endif else msgbox(0, "Success", "IniReadSectionNames worked!") endif Why is that? Is there something further to check with him?
      Autorun.inf
    • FrancescoDiMuro
      By FrancescoDiMuro
      Good morning community!
      I was working on a script which read the content of a .ini file to retrieve the file that has to open, and, based on the value of a second key stored in the .ini file, set the window on top, minimized or maximized...
      I did something like this, but seems to not work properly...
      Could anyone please tell me what I'm doing wrong?
      Thank you  
       
      #Region ;**** Directives created by AutoIt3Wrapper_GUI **** #AutoIt3Wrapper_Outfile_x64=prova.exe #EndRegion ;**** Directives created by AutoIt3Wrapper_GUI **** #include <ButtonConstants.au3> #include <GUIConstantsEx.au3> #include <StaticConstants.au3> #include <WindowsConstants.au3> #include <MsgBoxConstants.au3> #include <AutoItConstants.au3> ;#include <WinAPIEx.au3> #include <Array.au3> Local $sFileConfigurazione = @ScriptDir & "\configurazione_exe.ini" If(FileExists($sFileConfigurazione)) Then Local $aSezioneIni = IniReadSection($sFileConfigurazione, "CONFIGURAZIONE_EXE") If @error Then MsgBox($MB_ICONERROR, "Errore!", "Errore durante l'apertura del file: " & @CRLF & $sFileConfigurazione & @CRLF & "Errore: " & @error) Else ; Lancio dell'applicativo indicato nel file di configurazione Local $iPID = ShellExecute($aSezioneIni[1][1]) Local $hWnd If($iPID <> 0) Then Local $aWinList = WinList() For $i = 1 To $aWinList[0][0] If(WinGetProcess($aWinList[$i][1] = $iPID)) Then $hWnd = $aWinList[$i][1] EndIf Next Switch($aSezioneIni[2][1]) Case $aSezioneIni[2][1] = "MIN" ToolTip("MIN", 0, 0) WinSetState($hWnd, WinGetTitle($hWnd), @SW_MINIMIZE) Case $aSezioneIni[2][1] = "MAX" ToolTip("MAX", 0, 0) WinSetState($hWnd, WinGetTitle($hWnd), @SW_MAXIMIZE) Case $aSezioneIni[2][1] = "TOP" ToolTip("TOP", 0, 0) WinSetOnTop($hWnd, WinGetTitle($hWnd), $WINDOWS_ONTOP) EndSwitch EndIf EndIf EndIf And the .ini file is like this:
       
      [CONFIGURAZIONE_EXE] PercorsoExe=Here goes the path and the .exe to execute ModalitaAperturaExe=Here goes one of the value below /* TOP Shows the windows on top */ /* MIN Shows the window minimized */ /* MAX Shows the window maximized */  
    • ur
      By ur
      The below functions are to write data to a configuration or property file and also read them back.
      BuildLocation:C:\Build BuildExe : setup.exe Release:r9.7 Silent:No InstallPath:default Compare :No MartUpgrade :Yes Bit:64 ERwinUpgrade:No License_File:150416-1952 Navigator (ca.com).lic You can change the character from ":" to "=" or whatever based on your requirement and update the code also accordingly.
      Property.au3
    • ur
      By ur
      Hi,
       
      I have a property file format configuration file for our project.
      The sample file is as below.
      BuildLocation:C:\Build BuildExe:erwin Data Modeler r9.7 (64-bit)_2378.exe Release:r9.64.02 Silent:No InstallPath:default Compare :No MartUpgrade :Yes Bit:64 ERwinUpgrade:No License_File:150416-1952 Navigator (ca.com).lic To read this file, I am using below code.
      Func readConfig($sFilePath,$intStartCode) ;Usage: MsgBox(0,"Silent",readConfig(@ScriptDir&"\Config.txt","Silbent")) ;$sReplaceText = "Mani Prakash" ;$sFilePath = "C:\Users\KIRUD01\Desktop\Config.txt" ;$intStartCode = "BuildExe" $arrRetArray = "" $s = _FileReadToArray($sFilePath, $arrRetArray);Reading text file and saving it to array $s will show status of reading file.. For $i = 1 To UBound($arrRetArray)-1 $line = $arrRetArray[$i];retrieves taskengine text line by line If StringInStr($line, $intStartCode) Then ConsoleWrite ("Starting point "& $line & @CRLF) return StringStripWS(StringSplit($line,":")[2],$STR_STRIPLEADING + $STR_STRIPTRAILING ) EndIf if $i = UBound($arrRetArray)-1 then return "Not Found" Next EndFunc The above code is working to read the particular key value.
      But problem is , if I try to read the key "Bit" it is giving the value of key "BuildExe" as the line contains the word "bit"..
      Can you suggest how to do this. 
       
      If possible I need to fix writeConfig also.
       
      Func writeConfig($sFilePath,$intStartCode,$sReplaceText) ;$sReplaceText = "Mani Prakash" ;$sFilePath = "C:\Users\KIRUD01\Desktop\Config.txt" ;$intStartCode = "BuildExe" $arrRetArray = "" $s = _FileReadToArray($sFilePath, $arrRetArray);Reading text file and saving it to array $s will show status of reading file.. $intStartingPointFound = 0 For $i = 1 To UBound($arrRetArray)-1 $line = $arrRetArray[$i];retrieves taskengine text line by line If StringInStr($line, $intStartCode) Then $intStartingPointFound = 1;if found the starting point of the module to copy then set this variable to 1 ConsoleWrite ("Starting point " & @CRLF) $arrRetArray[$i] = $intStartCode & ": " & $sReplaceText ExitLoop EndIf if $i = UBound($arrRetArray)-1 then ConsoleWrite("Not Found" & @CRLF) Next _FileWriteFromArray ($sFilePath, $arrRetArray,1) EndFunc