How to save components to a file or stream (3) (Views: 704)
Problem/Question/Abstract: In D6, what's the best or usual way to stream an object to text so that it shows up just as it does when you copy an object to the clipboard or when you display a form as text? Answer: This example shows how to use the built-in VCL component streaming support to convert any component into a string and convert that string back into a component. function ComponentToString(Component: TComponent): string; var BinStream: TMemoryStream; StrStream: TStringStream; s: string; begin BinStream := TMemoryStream.Create; try StrStream := TStringStream.Create(s); try BinStream.WriteComponent(Component); BinStream.Seek(0, soFromBeginning); ObjectBinaryToText(BinStream, StrStream); StrStream.Seek(0, soFromBeginning); Result := StrStream.DataString; finally StrStream.Free; end; finally BinStream.Free end; end; function StringToComponent(Value: string): TComponent; var StrStream: TStringStream; BinStream: TMemoryStream; begin StrStream := TStringStream.Create(Value); try BinStream := TMemoryStream.Create; try ObjectTextToBinary(StrStream, BinStream); BinStream.Seek(0, soFromBeginning); Result := BinStream.ReadComponent(nil); finally BinStream.Free; end; finally StrStream.Free; end; end; |