Mega Code Archive

 
Categories / Delphi / Files
 

How to create and modify Application INI Files

Title: How to create and modify Application-INI-Files Question: You will keep all Application-related Infos in an Application-owned file? Answer: Here is a very handy sample Procedure. It used an Ini-File named 'PROJECT.INI' stored in the application-path. You must no values put in this File before your application runs - write your code - compile and run. If this File not exists - it is new created. If no value found in it - the default-value is stored and returned. With the default-values placed in your Source-code you can run everytime your application without editing this INI-File before. If you delete the INI-File your application starts with the coded default-values. If your Application is deinstalled the INI-File ist also deleted. No actions must be done in the Registry. type TAction = (taRead, taWrite); uses IniFiles; function SetupGet(cTyp: TAction; cSection, cKey, cDefault: string): string; { Working with Application-INI-Files cTyp taRead = Read taWrite = Write cSection Sectionname cKey Keyname cDefault Defaultvalue for the first call Return String from cSection+cKey Sample to read in old values: Edit1.Text := SetupGet(taRead,'Tax', 'Regional', '7'); Sample to write back changed values: SetupGet(taWrite,'Tax', 'Regional', Edit1.Text); } var INIFile: TIniFile; begin INIFile := TIniFile.create(ExtractFilePath(ParamStr(0)) + 'Projekt.INI'); with INIFile do begin case cTyp of taRead: begin // read in old values result := ReadString(cSection, cKey, ''); if (result = '') and (cDefault '') then begin Result := cDefault; WriteString(csection, cKey, cDefault); end; end; taWrite: begin // write back changed values result := cDefault; WriteString(csection, cKey, cDefault); end; end; end; INIFile.Free; end; // Place two Buttons and an Edit - Field in your Form. procedure TForm1.Button1Click(Sender: TObject); begin Edit1.Text := SetupGet(taRead, 'Tax', 'Regional', '7'); end; procedure TForm1.Button2Click(Sender: TObject); begin SetupGet(taWrite, 'Tax', 'Regional', Edit1.Text); end; { First run: Edit1.Text has '7' - change it to any value and exit the program. Second run: Edit1.Text has the value from your first run. The sample PROJECT.INI has this lines (e.g.): [Tax] Regional=9