Jump to content

Change values in config files


ur
 Share

Recommended Posts

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.

Link to comment
Share on other sites

  • Moderators

ur,

What code have you tried that has not worked?

M23

Public_Domain.png.2d871819fcb9957cf44f4514551a2935.png Any of my own code posted anywhere on the forum is available for use by others without any restriction of any kind

Open spoiler to see 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

 

Link to comment
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.

 

Link to comment
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 =.

Link to comment
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.

Link to comment
Share on other sites

  • Moderators

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

Public_Domain.png.2d871819fcb9957cf44f4514551a2935.png Any of my own code posted anywhere on the forum is available for use by others without any restriction of any kind

Open spoiler to see 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

 

Link to comment
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.

Link to comment
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

 

Link to comment
Share on other sites

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

Signature - my forum contributions:

Spoiler

UDF:

LFN - support for long file names (over 260 characters)

InputImpose - impose valid characters in an input control

TimeConvert - convert UTC to/from local time and/or reformat the string representation

AMF - accept multiple files from Windows Explorer context menu

DateDuration -  literal description of the difference between given dates

Apps:

Touch - set the "modified" timestamp of a file to current time

Show For Files - tray menu to show/hide files extensions, hidden & system files, and selection checkboxes

SPDiff - Single-Pane Text Diff

 

Link to comment
Share on other sites

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
Link to comment
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
 Share

×
×
  • Create New...