How to write a list of strings to the registry #88

Question
I want to save the contents of a string list to the registry and later read it back. How can I do this?

Save a list of strings to the registry. It will write each string as a key value with the key being the index of each string element and the value being the key.

procedure TDPRegistry.SaveStringListInRegistry(
  _RootKey: HKEY; _Localkey: String; Strings: TStrings
);
var
  TR: TRegIniFile;
  LStringIndex: Integer;
begin
  TR := TRegIniFile.Create('');
  try
    case _RootKey of // default is RootKey=HKEY_CURRENT_USER
      HKEY_CLASSES_ROOT,
      HKEY_CURRENT_USER,
      HKEY_LOCAL_MACHINE,
      HKEY_USERS,
      HKEY_PERFORMANCE_DATA,
      HKEY_CURRENT_CONFIG,
      HKEY_DYN_DATA: TR.RootKey := _RootKey;
    end;
    // make sure no entries for this section/ key
    TR.EraseSection(_Localkey);
    with TRegistry(TR) do
    begin
      if OpenKey(_Localkey, true) then
      begin
        try
          for LStringIndex := 0 to Strings.Count - 1 do
            WriteString (IntToStr(LStringIndex), Strings[LStringIndex]);
        finally
          CloseKey;
        end;
      end;
    end;
  finally
    TR.Free;
  end;
end;

{Get list of strings from registry}
procedure TDPRegistry.GetStringListFromRegistry(
  _RootKey: HKEY; _Localkey: String; Strings: TStrings
);
var
  TR: TRegIniFile;
  LStringIndex: Integer;
  RegKeyInfo: TRegKeyInfo;
begin
  Strings.Clear;  // start with no elements in string list
  TR := TRegIniFile.Create('');
  try
    case _RootKey of // default is  RootKey=HKEY_CURRENT_USER
      HKEY_CLASSES_ROOT,
      HKEY_CURRENT_USER,
      HKEY_LOCAL_MACHINE,
      HKEY_USERS,
      HKEY_PERFORMANCE_DATA,
      HKEY_CURRENT_CONFIG,
      HKEY_DYN_DATA: TR.RootKey := _RootKey;
    end;
    {TR.ReadSectionValues(_Localkey, Strings); doesn't work nicely because
    it returns strings as "1=Value", "2=Value"...}
    with TRegistry(TR) do
    begin
      if OpenKey(_Localkey, true) then
      begin
        try
          if (GetKeyInfo(RegKeyInfo)) then
          begin
            for LStringIndex := 0 to RegKeyInfo.NumValues - 1 do
              Strings.Add(ReadString(IntToStr(LStringIndex)));
          end;
        finally
          CloseKey;
        end;
      end;
    end;
  finally
    TR.Free;
  end;
end;
Original resource: The Delphi Pool
Author: Unknown
Added: 2009/08/24
Last updated: 2009/08/24