Using INI Files

From Lazarus wiki
Revision as of 17:41, 19 November 2011 by Sekelsenmat (talk | contribs) (→‎Example)
Jump to navigationJump to search

العربية (ar) Deutsch (de) English (en) español (es) suomi (fi) français (fr) polski (pl) русский (ru) 中文(中国大陆)‎ (zh_CN)

INI Files

Basic Information

INI files can be used to save basic user settings easily. With the INIfiles unit and the TINIFile class you can easily work with existing INI files. This unit is found in the FCL.

INI Files

INI Files use brackets to create and mark Sections, which contain keys and key values. A Key and its corresponding Value are separated with an equals sign (Key=Value). Section names are put inside square brackets ([Section]). INI Files are used less than XML files for string storage, because INI files don't handle large strings very well.

Ini file reading example

The console application bellow shows how to read ini files. To test it one should create the following ini file with the name "C:\DB.ini". Edit it to so it contains a section called INIDB and the following keys and values:


Now let's move on the the code.. <Delphi> Program Project1;

{$mode objfpc}{$H+}






 INI := TINIFile.Create('C:\DB.ini');
 Author := INI.ReadString('INIDB','Author',);
 Pass := INI.ReadString('INIDB','Pass',);
 DBFile := INI.ReadString('INIDB','DBFile',);
 if Pass <>  then
   Writeln('Password Required');
     if not PassEnter = Pass then Writeln('Wrong Password');
   until(PassEnter = Pass);
   Writeln('Correct Password');
 Writeln('Author : '+Author);
 Writeln('File : '+DBFile);
 Writeln('Password : '+Pass);
 Ini.Free; // After we used ini file, we must call the Free method of object

end. </Delphi>

Objects to know

In the TINIFile class there are many different properties, procedures and functions that can be used.

CaseSensitive - This property allows you to say if the keys and sections are case sensitive or not. By default they aren't.

ReadString - Has 3 constant statements. The first one is the section to search in. The second one is the key to look for. The third one is a default string in case the key and/or section searched for is not found.

WriteString - has three constant statements, too. The first is the section. The second is the key and the last is the value that you want to write. If the key and section exist already, the key will be overwritten with the new value..

ReadSections - Will allow you to to take the sections from the INI file and put them in a TStrings class (or TStringList with the AS operator).

DeleteKey - Remove an existing key from a specific section.

EraseSection - Remove a section and all its data.

There are more procedures and functions but this is enough to get you started.

Last words...

Here: FreePascal documentation on INI files you can learn all about INI Files.

See also