Re: outputting settings to a file..Posted by webmaster Guido on October 22, 2001
In Reply to: outputting settings to a file.. posted by p12174 Doug on October
22, 2001 Even if you don't want to use the standard INI-file format, I advise you to start by trying the following example and afterwards build on that code to develop your own.
procedure TForm1.ButtonWriteClick(Sender: TObject); var IniFile: TIniFile; begin IniFile := TIniFile.Create('C:\Test\Settings.ini'); with IniFile do begin WriteBool('ProjectSettings', 'FirstChoice', CheckBox1.Checked); WriteBool('ProjectSettings', 'SecondChoice', CheckBox2.Checked); // and so on for other settings... Free; end; end; procedure TForm1.ButtonReadClick(Sender: TObject); var IniFile: TIniFile; begin IniFile := TIniFile.Create('C:\Test\Settings.ini'); with IniFile do begin CheckBox1.Checked := ReadBool('ProjectSettings', 'FirstChoice', False); CheckBox2.Checked := ReadBool('ProjectSettings', 'SecondChoice', False); // and so on for other settings... Free; end; end;
TInifile features:
function BoolToIniText(Name: string; Value: Boolean): string; var C: char; begin if Value then C := '1' else C := '0'; Result := Name + ' ' + C; end; function IniTextToBool(S: string; FileFound, DefaultValue: Boolean): Boolean; var C: char; begin if not FileFound then Result := DefaultValue else begin C := S[Length(S)]; // the last character Result := C = '1'; end; end; Next, we can build on the INI-file example:
procedure TForm1.ButtonWriteClick(Sender: TObject); var MyIni: TStringList; begin MyIni := TStringList.Create; with MyIni do begin Add('ProjectSettings'); Add(BoolToIniText('FirstChoice', CheckBox1.Checked)); Add(BoolToIniText('SecondChoice', CheckBox2.Checked)); // and so on for other settings... SaveToFile('C:\Test\Settings.ini'); Free; end; end; Reading back the data is easy if it is done in the same sequence as you have written it. But it involves quite a bit more if you want to be able to read at random, like you can with TInifile!
procedure TForm1.ButtonReadClick(Sender: TObject); var MyIni: TStringList; Found: Boolean; begin Found := FileExists('C:\Test\Settings.ini'); MyIni := TStringList.Create; MyIni.LoadFromFile('C:\Test\Settings.ini'); // skip the section header 'ProjectSettings' // so start with the SECOND line CheckBox1.Checked := IniTextToBool(MyIni[1], Found, False); CheckBox2.Checked := IniTextToBool(MyIni[2], Found, False); // and so on for other lines... MyIni.Free; end; Tip: for storing integer values, you can use the Delphi functions IntToStr() and StrToInt() to make the necessary conversions. |