Saving a TObject to a File

David picture David · Mar 30, 2009 · Viewed 13.5k times · Source

How can one save an Object, in its current state, to a file? So that it can immediately be read and restored with all its variables.

Answer

Francesca picture Francesca · Mar 30, 2009

As already stated, the easiest way is to use a Stream and its WriteComponent and ReadComponent methods.
But be aware that :
- it works for descendants of TComponent, not plain TObject;
- only for the published properties (those saved in a dfm), not the public ones nor (a fortiori) the privwte ones;
- you have to pay a special attention for the Name property when restoring the component.

You may find some code you could use in these SO answers: Replace visual component at runtime in Delphi, Duplicating components at Run-Time