2006. augusztus 27., vasárnap

How to write a list of strings to the registry


Problem/Question/Abstract:

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

Answer:

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;
    TR.EraseSection(_Localkey); {make sure no entries for this section/ key}
    with TRegistry(TR) do
    begin
      if OpenKey(_Localkey, true) then
      begin
        try
          for LStringIndex := 0 to Strings.Count - 1 do
          begin
            WriteString(IntToStr(LStringIndex), Strings[LStringIndex]);
          end; {for each string in the list}
        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
            begin
              Strings.Add(ReadString(IntToStr(LStringIndex)));
            end; {for each value associated with this key}
          end; {got key information}
        finally
          CloseKey;
        end;
      end;
    end;
  finally
    TR.Free;
  end;
end;

Nincsenek megjegyzések:

Megjegyzés küldése