2007. június 28., csütörtök

Search for a substring in a registry tree


Problem/Question/Abstract:

How do I iterate through the entries of HKLM and look for a particular string?

Answer:

Searching for a substring in a registry tree:

procedure SearchRegistry(aRoot: HKEY; searchfor: string; resultlist: TStrings);

  procedure EnumKey(const keyname: string);

    function VName(const valuename: string): string;
    begin
      if Length(valuename) = 0 then
        Result := '@'
      else
        Result := valuename;
    end;

  var
    reg: TRegistry;
    temp: TStringList;
    S: string;
    i: Integer;
  begin
    reg := TRegistry.Create;
    try
      reg.Rootkey := aRoot;
      if reg.OpenKeyReadOnly(keyname) then
      begin
        {Enumerate the values}
        temp := TStringList.Create;
        try
          reg.GetValueNames(temp);
          for i := 0 to temp.Count - 1 do
          begin
            if reg.GetDatatype(temp[i]) = rdString then
            begin
              S := reg.ReadString(temp[i]);
              if Length(S) > 0 then
              begin
                if Pos(searchfor, AnsiUpperCase(S)) > 0 then
                  resultlist.add(Format('%s %s ="%s"', [keyname, Vname(temp[i]), S]));
              end;
            end;
          end;
          temp.Clear;
          {Enumerate the subkeys}
          if reg.HasSubKeys then
          begin
            reg.GetKeyNames(temp);
            for i := 0 to temp.count - 1 do
              EnumKey(keyname + '\' + temp[i]);
          end;
        finally
          temp.free;
        end;
      end;
      reg.CloseKey;
    finally
      reg.free;
    end;
  end;

begin
  searchfor := AnsiUpperCase(searchfor);
  EnumKey(EmptyStr);
end;

Used like this:

procedure TForm1.Button1Click(Sender: TObject);
begin
  Memo1.clear;
  Screen.Cursor := crHourglass;
  try
    SearchRegistry(HKEY_CLASSES_ROOT, 'internet', memo1.lines);
  finally
    Screen.Cursor := crDefault;
  end;
end;

Nincsenek megjegyzések:

Megjegyzés küldése