Use Windows' Registry as INI files in Delphi

Posted by John, DelphiLand Team on August 16, 2008

In Reply to Re: Write/copy ini section to registry posted by Bobp12404 on August 09, 2008

: From the ini file:
: [Images]
: G:\Pics\culled\bird.jpg=Unique brief description of this image
: C:\Pics\Latest\bird.tif=Original image as shot from camera
: [Music]
: C:\Songs\Jazz\a_name_of_a_song.mp3=Unique brief description of this song
: E:\Songs_Saved\Guitar\a_name_of_a_song.wav=Unique brief description of this song
: G:\Songs from another directory\Drums\a_name_of_a_song.aac=Wow they were loud
:
: To these registry keys:

: HKEY_CURRENT_USER\Software\MyApp\Images
: HKEY_CURRENT_USER\Software\MyApp\Music
:
: Essentialy, I have some listviews which are loaded from text/ini files that I want to be able to 'backup' to the registry. Or at least have another option, distinct from ini, for saving the data. I have just heard about TRegIniFile, and it sounds like it ought to be able to do both, but I don't understand how to use it to write to the registry.

Better use Delphi's TRegistryIniFile instead of TRegIniFile, it has more possibilities and it's more compatible with TIniFile.

Also, if you switch from INI files to the registry, you can rewrite your application with a minimum of coding changes: only change the code for Create.
TRegistryIniFile interprets the FileName property as a subkey under the registry's root key, HKEY_CURRENT_USER by default. So, instead of:

IniFile := TIniFile.Create('C:\Software\MyApp');

you code it as:

RegistryIniFile := TRegistryIniFile.Create('Software\MyApp');

Most methods are the same as in TIniFile: ReadString, ReadInteger, ReadFloat,..., WriteString, WriteInteger, WriteFloat,..., ReadSection, ReadSections, DeleteKey, EraseSection, and so on... Don't worry about what happens behind the scenes: sections are treated as sub-keys in the registry, and data entries under a section are treated as ident/data value pairs of that sub-key.
For example, the following code writes an ident/value pair in the key HKEY_CURRENT_USER\Software\MyApp\Images:

var
  RIniFile: TRegistryIniFile;
begin
  RIniFile := TRegistryIniFile.Create('Software\MyApp');
  RIniFile.WriteString('Images', C:\Pics\Latest\bird.tif', 'Original image as shot from camera');

The key is created automatically if it doesn't exist already, otherwise you overwrite the existing value(s).

PS: Sorry for the delay, but I was away for a vacation. Should have notified webmaster Guido though... I'll try to make up, during the next days I'll post some more example source code.

Best regards,
John, DelphiLand Team

Related articles

       

Follow Ups