Author: Jonas Bilinkevicius I have a component TZzz (descends from TComponent) and I want to implement some saving/ restoring capabilities for it. Here's my point. I want to place a TZzz component in a form and export this object to a file. Later, I want import that file to another TZzz object in another form (only for copying the properties from one object to another). Any ideas? Answer: Here is a component I wrote which I use often. Simply derive from TPersistentComponent and you can then stream it in and out either directly to a stream or to a file as well. You will have to implement the FindMethod method yourself. 1 unit Unit1; 2 3 interface 4 5 uses 6 Classes, Sysutils; 7 8 const 9 cFileDoesNotExist = 'File Does Not Exist %0s'; 10 cDefaultBufSize = 4096; 11 12 type 13 TPersistComponent = class(TComponent) 14 15 private 16 FStreamLoad: Boolean; 17 protected 18 property StreamLoad: Boolean read FSTreamLoad; 19 procedure FindMethod(Reader: TReader; const MethodName: string; var Address: 20 Pointer; 21 var Error: Boolean); virtual; 22 public 23 procedure LoadFromFile(const FileName: string; const Init: Boolean = False); 24 virtual; 25 procedure SaveToFile(const FileName: string); virtual; 26 procedure LoadFromStream(Stream: TStream); virtual; 27 procedure SaveToStream(Stream: TStream); virtual; 28 end; 29 30 implementation 31 32 procedure TPersistComponent.FindMethod(Reader: TReader; const MethodName: string; 33 var Address: Pointer; var Error: Boolean); 34 begin 35 Error := False; 36 end; 37 38 procedure TPersistComponent.LoadFromFile(const FileName: string; const Init: 39 Boolean = 40 False); 41 var 42 FS: TFileStream; 43 begin 44 if FileExists(Filename) then 45 begin 46 FS := TFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite); 47 try 48 LoadFromStream(FS); 49 finally 50 FS.Free; 51 end; 52 end 53 else 54 raise Exception.CreateFmt(cFileDoesNotExist, [FileName]); 55 end; 56 57 procedure TPersistComponent.LoadFromStream(Stream: TStream); 58 var 59 Reader: TReader; 60 begin 61 Reader := TReader.Create(Stream, cDefaultBufSize); 62 try 63 {Reader.OnFindMethod := FindMethod;} 64 FStreamLoad := True; 65 Reader.OnFindMethod := FindMethod; 66 Reader.BeginReferences; 67 Reader.Root := Owner; 68 Reader.ReadComponent(Self); 69 Reader.EndReferences; 70 Loaded; 71 finally 72 FStreamLoad := False; 73 Reader.Free; 74 end; 75 end; 76 77 procedure TPersistComponent.SaveToFile(const FileName: string); 78 var 79 FS: TFileStream; 80 begin 81 FS := TFileStream.Create(FileName, fmCreate); 82 try 83 SaveToStream(FS); 84 finally 85 FS.Free; 86 end; 87 end; 88 89 procedure TPersistComponent.SaveToStream(Stream: TStream); 90 var 91 Writer: TWriter; 92 begin 93 Writer := TWriter.Create(Stream, cDefaultBufSize); 94 try 95 Writer.Root := Owner; 96 Writer.WriteComponent(Self); 97 finally 98 Writer.Free; 99 end; 100 end; 101 102 end.