Author: William Gerbert
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.
1
2 procedure TDPRegistry.SaveStringListInRegistry(_RootKey: HKEY; _Localkey: string;
3 Strings: TStrings);
4 var
5 TR: TRegIniFile;
6 LStringIndex: Integer;
7 begin
8 TR := TRegIniFile.Create('');
9 try
10 case _RootKey of { default is RootKey=HKEY_CURRENT_USER }
11 HKEY_CLASSES_ROOT,
12 HKEY_CURRENT_USER,
13 HKEY_LOCAL_MACHINE,
14 HKEY_USERS,
15 HKEY_PERFORMANCE_DATA,
16 HKEY_CURRENT_CONFIG,
17 HKEY_DYN_DATA: TR.RootKey := _RootKey;
18 end;
19 TR.EraseSection(_Localkey); {make sure no entries for this section/ key}
20 with TRegistry(TR) do
21 begin
22 if OpenKey(_Localkey, true) then
23 begin
24 try
25 for LStringIndex := 0 to Strings.Count - 1 do
26 begin
27 WriteString(IntToStr(LStringIndex), Strings[LStringIndex]);
28 end; {for each string in the list}
29 finally
30 CloseKey;
31 end;
32 end;
33 end;
34 finally
35 TR.Free;
36 end;
37 end;
38
39 {Get list of strings from registry}
40
41 procedure TDPRegistry.GetStringListFromRegistry(_RootKey: HKEY; _Localkey: string;
42 Strings: TStrings);
43 var
44 TR: TRegIniFile;
45 LStringIndex: Integer;
46 RegKeyInfo: TRegKeyInfo;
47 begin
48 Strings.Clear; {start with no elements in string list}
49 TR := TRegIniFile.Create('');
50 try
51 case _RootKey of { default is RootKey=HKEY_CURRENT_USER }
52 HKEY_CLASSES_ROOT,
53 HKEY_CURRENT_USER,
54 HKEY_LOCAL_MACHINE,
55 HKEY_USERS,
56 HKEY_PERFORMANCE_DATA,
57 HKEY_CURRENT_CONFIG,
58 HKEY_DYN_DATA: TR.RootKey := _RootKey;
59 end;
60 {TR.ReadSectionValues(_Localkey, Strings); doesn't work nicely because it
61 returns strings as "1=Value", "2=Value"...}
62 with TRegistry(TR) do
63 begin
64 if OpenKey(_Localkey, true) then
65 begin
66 try
67 if (GetKeyInfo(RegKeyInfo)) then
68 begin
69 for LStringIndex := 0 to RegKeyInfo.NumValues - 1 do
70 begin
71 Strings.Add(ReadString(IntToStr(LStringIndex)));
72 end; {for each value associated with this key}
73 end; {got key information}
74 finally
75 CloseKey;
76 end;
77 end;
78 end;
79 finally
80 TR.Free;
81 end;
82 end;
|