TStringList.SaveToStream TStringStream.SaveToStream
http://marc.durdin.net/2011/10/comparing-tstringstream-vs-tstringlist.html
There are two methods widely used in Delphi code for reading and writing strings to/from streams with Delphi,
that initially seem pretty similar in their behaviour.
These are TStrings.SaveToStream and TStringStream.SaveToStream (or SaveToFile in either case):
procedure TForm1.SaveToFile; const AString = 'This is some Unicode text'#13 + 'Test Unicode © Δ א'; begin with TStringList.Create do try Text := AString; SaveToFile('TStringList UTF8.txt', TEncoding.UTF8); finally Free; end; with TStringStream.Create(AString, TEncoding.UTF8) do try SaveToFile('TStringStream UTF8.txt'); finally Free; end; end;
But there are several crucial differences in what is written to the stream between these two methods:
- TStringList prepends the preamble bytes for the encoding (in this case, #$EF#$BB#$BF)
- TStringList appends a new line #$0D#$0A to the file, if your text does not already end in a new line.
- TStringList converts any single line breaking characters in the text (e.g. #$0D or#$0A) into #$0D#$0A.
The following hex dumps may show this more clearly:
InsdertEF BB BF 54 68 69 73 20 69 73 20 73 6F 6D 65 20TStringList UTF8.txt
55 6E 69 63 6F 64 65 20 74 65 78 74 0D 0A 54 65 <-- converted from 0x0D
73 74 20 55 6E 69 63 6F 64 65 20 C2 A9 20 CE 94
20 D7 90 0D 0A <-- append
54 68 69 73 20 69 73 20 73 6F 6D 65 20 55 6E 69
63 6F 64 65 20 74 65 78 74 0D 54 65 73 74 20 55
6E 69 63 6F 64 65 20 C2 A9 20 CE 94 20 D7 90
TStringStream UTF8.txt
Make sure you know how your files will be read and whether these differences are important to the target application.
Basically, TStringList is typically not appropriate for streaming strings without modification.
TStringStream is your friend here.
But if you need the preamble, and just the preamble, then you'll have to do a little more work;
you won't be able to use TStringStream.SaveToFile.
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本