Did you know that all Delphi streams automatically support persisting/loading components, just as the IDE uses it? While looking today how again to persist a component state, I came across the methods WriteComponent and ReadComponent. I honestly never saw those before. Therefore persisting a component into a stream is just one line, when you want to have the data in text form, simply use ObjectBinaryToText and ObjectTextToBinary for the transformations. Great, how easy life can be. This method works fo published properties only, but most often this will do just fine.
// code to stream component state to file FileStream := TFileStream.Create(Filename, fmCreate); BinStream := TMemoryStream.Create; try BinStream.WriteComponent(YourComponent); BinStream.Position := 0; ObjectBinaryToText(BinStream, FileStream); finally BinStream.Free; FileStream.Free; end;
// code to stream component state to file
try
finally
end
// code to load component streamed component from file FileStream := TFileStream.Create(Filename, fmOpenRead); BinStream := TMemoryStream.Create; try ObjectTextToBinary(FileStream, BinStream); BinStream.Position := 0; BinStream.ReadComponent(YourComponent); finally BinStream.Free; FileStream.Free; end;
// code to load component streamed component from file
BinStream := TMemoryStream.Create; try
As a note, I am sure, I knew this before as I have done that a few years ago already, but hey, sometimes you just forget and rediscover and you are happy again...
The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.
Theme design by Jelle Druyts