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.
About the Author
The author has not added a profile short description yet.
Show Profile
Related Topics
Windows Batch Script: Computer Shutdown
Tutorial | 2 Comments
Lazarus: Load File as Byte Array and save Byte Array as File
Tutorial | 0 Comments
Delphi/Lazarus: 3 Ways to round a Number to X Decimal Places
Tutorial | 7 Comments
Delphi: Global Treatment of Errors (Exceptions)
Tutorial | 0 Comments
How to Replace multiple Texts at the same Time
Tutorial | 0 Comments
Delphi/Lazarus: How to set up a Link to a Website in an Application
Tutorial | 0 Comments
Delphi: Multiline Caption for TLabel (at Run Time and Design Time)
Tutorial | 1 Comment
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.