Author: Tomas Rutkauskas
I have written a component which uses TCollections as properties. Now I need a way
to save the TCollectionItems to a file. How can I do that?
Answer:
You may try these routines. I have tested them with TStatusBar.Panels collection
and they worked for me:
1 2 procedure LoadCollectionFromStream(Stream: TStream; Collection: TCollection);
3 begin4 with TReader.Create(Stream, 4096) do5 try6 CheckValue(vaCollection);
7 ReadCollection(Collection);
8 finally9 Free;
10 end;
11 end;
12 13 procedure LoadCollectionFromFile(const FileName: string; Collection: TCollection);
14 var15 FS: TFileStream;
16 begin17 FS := TFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite);
18 try19 LoadCollectionFromStream(FS, Collection);
20 finally21 FS.Free;
22 end;
23 end;
24 25 procedure SaveCollectionToStream(Collection: TCollection; Stream: TStream);
26 begin27 with TWriter.Create(Stream, 4096) do28 try29 WriteCollection(Collection);
30 finally31 Free;
32 end;
33 end;
34 35 procedure SaveCollectionToFile(Collection: TCollection; const FileName: string);
36 var37 FS: TFileStream;
38 begin39 FS := TFileStream.Create(FileName, fmCreate or fmShareDenyWrite);
40 try41 SaveCollectionToStream(Collection, FS);
42 finally43 FS.Free;
44 end;
45 end;
Note: It's obvious, the Collection variable must point to the initialized instance
of a TCollection
descendant.