44 Votes

Delphi/Lazarus: Store and Save MemoryStream in FileStream

Info by Delphian | 2013-07-29 at 14:28

In this small example, I would like to show you, how you are able to store a MemoryStream into a FileStream in order to save it thereafter.

This code can be used both in Delphi and Lazarus and looks like:

var
  fs: TFileStream;
begin

  // ms is a given TMemoryStream 

  fs := TFileStream.Create('C:\test.txt', fmCreate);

  try

     if ms.Size>0 then begin
       ms.Position:=0;
       fs.CopyFrom(ms, ms.Size);
     end;

  finally
     fs.free;
  end;   

end;

In this code, "ms" is our MemoryStream we would like to save. With fs.CopyFrom(ms, ms.Size) we can copy the MemoryStream in its full length into the FileStream "fs". Here, it is important, to ensure before, that that position of "ms" stands on 0. So, we set this position by using ms.Position:=0 to 0 before copying. Otherwise, the stream cannot be read from the beginning.

Lazarus and umlauts/Unicode characters in file names

When using this example with Lazarus and there may occur umlauts or other Unicode characters in the name of the file (here "C:\test.txt"), you should simply replace TFileStream with TFileStreamUTF8 at both positions (declaration and create). When not doing so, and error can occur there.

ReplyPositiveNegative

About the Author

AvatarThe author has not added a profile short description yet.
Show Profile

 

Related Topics

Important Note

Please note: The contributions published on askingbox.com are contributions of users and should not substitute professional advice. They are not verified by independents and do not necessarily reflect the opinion of askingbox.com. Learn more.

Participate

Ask your own question or write your own article on askingbox.com. That’s how it’s done.