Code archives/File Utilities/Config file reader/changer

This code has been declared by its author to be Public Domain code.

Download source code

Config file reader/changer by Andres2006
Variables aren't case sensitive.

Entry example:
variable$=value$
Const ConfigFile$ = "config.cfg"

Type file
	Field txt$
End Type

Function ConfigValue$(variable$)
	rf = ReadFile(ConfigFile$)
	If rf
		While Not Eof(rf)
			txt$ = ReadLine$(rf)
			If Left$(Lower(txt$), Instr(txt$, "=")) = Lower(variable$ + "=")
				Return Right$(txt$, Len(txt$) - Instr(txt$, "="))
			EndIf
		Wend
		CloseFile rf
	EndIf
	Return False
End Function

Function ChangeConfigValue(variable$, value$)
	rf = ReadFile(ConfigFile$)
	If rf
		For this.file = Each file
			Delete this
		Next
		While Not Eof(rf)
			this.file = New file
				this\txt$ = ReadLine$(rf)
		Wend
		CloseFile rf
	EndIf
	
	wf = WriteFile("config.cfg")
	If wf
		For this.file = Each file
			If Left$(Lower(this\txt$), Instr(this\txt$, "=")) = Lower(variable$ + "=")
				WriteLine wf, Left$(this\txt$, Instr(this\txt$, "=")) + value$
			Else
				WriteLine wf, this\txt$
			EndIf
		Next
		CloseFile wf
	EndIf
End Function

Comments

andy_mc2008
It would be good to have a working example of this working


Mike Barwise2008
For the purposes of getting it working:

Create a file called config.cfg and place it in the same directory as your code.

Inside the .cfg file, as a test, put:
"Entry1=Hello!"

Then within your code, to get it working, do:

DebugLog ConfigValue$( "Entry1" )

Your debuglog output should say 'Hello!'


Code Archives Forum