Jump to content
ur

Change values in config files

Recommended Posts

ur

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
Melba23

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
aiter

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
ur
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
ur
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
Melba23

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
AutoBert

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
InunoTaishou

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
orbs

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
ur

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

    • nacerbaaziz
      By nacerbaaziz
      hi dears
      am using an ini files as a History
      Sometimes the file size is be larger to 5 MB
      AutoIt does not recognize the full content of the file
      When I did a search to find out why, I discovered that INI files could not be read if they size larger than 64 KB.
      for that I preferred to ask here if is there any way to bypass this obstacle.
      The contents of the file are  as follows
      [filesList]
      c:\...\...\f1.mp3=00:15:20
      c:\...\...\f2.mp3=00:10:20
      c:\...\...\f3.wav=00:59:20
      ....... Etc
      This is the section for reading the file (adapted from my main script)

      case $continue     Local $aArray = IniReadSection($WaitingListFile, StringEncrypt(true, "filesList", $MyPassword))     If Not @error Then Opt("GUICloseOnESC", 1) _GUICtrlListView_DeleteAllItems($scList)         For $i = 1 To $aArray[0][0] $path = path_list(StringEncrypt(false, $aArray[$i][0], $MyPassWord), 1) if FileExists(StringEncrypt(false, $aArray[$i][0], $MyPassWord)) then GUICtrlCreateListViewItem(_GetFileName(FileGetLongName(StringEncrypt(false, $aArray[$i][0], $MyPassWord))) & Opt("GUIDataSeparatorChar") & " : " & Opt("GUIDataSeparatorChar") & FileGetLongName(StringEncrypt(false, $aArray[$i][0], $MyPassWord)), $scList) else $path = $path endIf         Next GUISetState(@sw_disable, $hGUI) GUISetState(@sw_show, $hGUI2) GUICtrlSetState($SClist, $GUI_FOCUS) else if $accessibilitymode = 1 then speak(str("listEmpty")) endIf endIf
      Is there any way to solve this problem, please?
      am waiting your answers...
      Greetings to All
    • AndreasNWWWWW
      By AndreasNWWWWW
      Hi, i'm just curious is there a way to sort an ini file after largest first?
      my inifiles writes itself like this
      14=500
      13=GREY
      12=500
      11=600
      10=600
      9=600
      8=700
      7=700
      5=600
      3=600
      2=800
      1=700
      15=GREY
      4=GREY
       
      but is there a way so i can get it sortet 
      15
      14
      13
      12 
      etc?
    • AndreasNWWWWW
      By AndreasNWWWWW
      Hi, i'm curious if this is even possible, i want to do an action if the ini file contains current values under a section.
      for my test i'm looking for 100,200,300,400,500
      and if any of those excits i want to pop a msgbox with the number in the section.
      i can in my example find one, but it does not check everyone. why?  what am i missing?
      Local $iscore810[5] = [100,200,300,400,500] Local $iMax800 = 5 While 1 ;~     Send("{pause}") ;;func les ini fil     $var = IniReadSection("Area.ini", "modus")     If @error Then         MsgBox(4096, "Error", "Unable to read section.")     Else          For $number = 1 To $var[0][0] If $var[$number][1] == $iscore810[3] Then       MsgBox($MB_SYSTEMMODAL, "FAnt den på", $var[$number][0], 5) EndIf                       Next     EndIf     exit WEnd  
    • Pike
      By Pike
      Hello Everyone,
      New Guy here. This is a two-part question, hopefully easy enough though. I know it's ugly coding, this is because I have only a couple hours worth of coding experience and could really use some help.
      1) When I single click the button I want one action (like playing a sound clip) and when I double click the button I want a different action (such as opening dialogue box to ask for soundclip directory address). At the bottom of the script I made a comment which one I would like single click versus double click.
      2) I can not get the FileOpenDialogue to save the file address to the config.ini file at the 'One' position on the .ini.
      #include <ButtonConstants.au3> #include <GUIConstantsEx.au3> #include <WindowsConstants.au3> #include <MsgBoxConstants.au3> #include <FileConstants.au3> #include <AutoItConstants.au3> #include <Sound.au3> Opt('MustDeclareVars', 1) Opt("GUIOnEventMode", 1) Global $OneID _Main() Func _Main() GUICreate("Form1", 156, 86, 281, 276) $OneID = GUICtrlCreateButton("Button", 15, 17, 122, 37) GUICtrlSetOnEvent($OneID, "OnOne") GUISetOnEvent($GUI_EVENT_CLOSE, "OnExit") GUISetState() While 1 While 1 Sleep(1000) WEnd WEnd EndFunc ;---------------Functions------------- While 1 Sleep(100) WEnd Func OnOne() ; ******************Single Click for this action**************** $OneID = IniRead("config.ini", "Config", "One", $OneID) If $OneID = True Then SoundPlay($OneID, @HotKeyPressed) Else ; *******Double Click for this action*****And Help Saving File Address to config.ini 'One'*********** $OneID = FileOpenDialog("Select file", @WorkingDir, "All (*.*)") IniWrite("config.ini", "Config", "One", $OneID) $OneID = InputBox("Enter Information", "Short Name for File?", "") IniWrite("config.ini", "Config", "NameOne", $OneID) EndIf EndFunc Any help would be greatly appreciated, and if you need anymore clarity as to what exactly I'm trying to do, please do not hesitate to ask. Thanks so much!
      Pike
    • kartune
      By kartune
      Hi, i would like to know if there is a possible way to use subsections for ini files?
      For example, my ini file would look something like this:
       
      Clientname.ini
      [Info]
      Country=USA
      Type=Distributor
       
      [Costs]
      [[JAN]] <----- subsection
      cost1=----
      cost2=----
      [[FEB]]
      cost1=----
      cost2=----
       
      [Sales]
      [[JAN]] <----- subsection
      sale1=----
      sale2=----
      [[FEB]]
      sale1=----
      sale2=----
       
      [Profits]
      [[JAN]] <----- subsection
      prof1=----
      prof2=----
      [[FEB]]
      prof1=----
      prof2=----
       
      The sales would be inputed everyday by the script, and then whenever viewed, i would be using an array to view every sale/cost/profit under the subsection
       
       
      Thanks for your time!
×