Function: IniRead()
Re: Function: IniRead()
Rewritten more flexible function
Re: Function: IniRead()
Returns a key named filePath. I have to delete it every time. Can I prevent this key from arrivingtoralf wrote: ↑27 May 2019, 06:46Hi there,
This would be my mod of the class.
Basically, I extended it with handling default values, changed the While to a For Loop and modified the RegEx to handle comments correctly. Thus, I hope it is more robust against human interaction with the ini file.Code: Select all
IniFileName := A_ScriptDir "\MyIniFile1.ini" If !FileExist( IniFileName ){ Content = ( [Section1] Key1=Section 1, Key 1 Key2=Section 1, Key 2 ;comment with [Section Name] ;[Commented Section] ; comment with [Commented Section Name] ; [Commented Section indented] [Section2] Key1=Section 2, Key 1 Key2=Section 2, Key 2 Key3=Text with = as a test ;Key4=a comment ; Key5=a comment indented ; comment = with equal sign Key6 = Spaces around = Key7=Key indented ) FileAppend, %Content%, %IniFileName% } DefaultValues := {Section1:{Key2: "Value exists in INI" , Key4: "Value from Default"} , "Section_test":{Key1: A_ScriptDir , 4: A_USerName }} oIni := new IniFileObj( IniFileName, DefaultValues ) MsgBox, % Obj2String( oIni ) ;- display all values oIni := new IniFileObj( A_ScriptDir "\MyIniFile2.ini", ,true ) If !FileExist(A_ScriptDir "\MyIniFile2.ini") oIni.section3 := { key1: "this is section three, key one.." } MsgBox, % Obj2String( oIni ) ;- display all values ExitApp class IniFileObj { __New( filePath, DefaultValues := "", saveOnExit:=false ){ For Section, KeysAndValues in DefaultValues { this[Section]:=[] For key, value in KeysAndValues this[Section].Insert(key,value) } this.filePath := filePath For i, thisLine in StrSplit( FileOpen(filePath,"r").Read(), "`n", "`r" ) If RegExMatch(thisLine,"^\s*(?<!;)((\[(?<Section>.*?)\])|(?<Key>\w+)\s*=(?<Value>.*)$)",_) _Key ? this[thisSection].Insert(_key,_value) : "", _Section ? (thisSection:=_Section, !this.Haskey(thisSection) ? this[thisSection]:=[]) saveOnExit ? OnExit( ObjBindMethod(this, "Save") ) } Save(){ For Section, KeysAndValues in this For key, value in KeysAndValues IniWrite, % value, % this.filePath, % Section, % key } } Obj2String(o,ind="",indChar=" ") { For i, v in o l .= (l ? "`r`n" : "") ind i " - " v, l .= IsObject(v) ? "`r`n" %A_ThisFunc%(v, ind indChar, indChar) : "" return l }
Obj.Delete(filePath)
Re: Function: IniRead()
In this key the object stores the file path for it to be able to save it in that file when it’s save method is called.
You could use a different key/parameter name. Or you could write custome get/set methods that store or read to a special object within the class so that the file path key is hidden.
You could use a different key/parameter name. Or you could write custome get/set methods that store or read to a special object within the class so that the file path key is hidden.
ciao
toralf
toralf