When you use pure string operations, your existing code will often port to Delphi 2009 with no major obstacle. When you are saving your string data to files or in-memory buffers, it is much easier to see things go wrong54.
The following is an example of a misused memory stream, in which data is inserted and extracted using different encodings, which doesn't force a conversion, but makes the system consider the characters of a different type than they actually are and mix them up: var memStr: TMemoryStream; begi n memStr := TMemoryStream.Create; try
LoadFromFile ( 'StreamTroubles_MainForm.pas'); Memo1.Lines.SaveToStream(memStr, TEncoding.UTF8); memStr.Position := 0; // reset
Memo2.Lines.LoadFromStream(memStr, TEncoding.Unicode); fi nal ly memStr.Free; end;
Executing this code results in a totally garbled content for Memo2. Now if in this specific code snippet the error is quite glaring, in most real-world situations you can bump into the same effect in much more subtle ways.
The number one recommendation, whenever saving to a file, is to save the BOM, to make it clear in which format it is55. This is no more difficult to achieve when working in memory, because even if you don't remember the actual format, Delphi's streaming code adds the proper BOM even to a memory stream.
54 I wish a mismatch of the BOM in the file with the preamble of the requested encoding used for loading would raise an exception, as this would make a little more sense. Of course, you could always read the corresponding bytes, rather than using strings, in case of low-level operations you want to fully control.
55 In the previous chapter, in the section "Streams and Encodings"we saw how to define a class helper for the TStrings class to change the default encoding for streaming. Refer to that example as a way to customize the behavior of your existing code without having to update it in many places.
So you could fix the program above by calling the LoadFromStream method with no encoding, letting the system check the format declared in the stream itself:
Was this article helpful?
What you need to know about… Project Management Made Easy! Project management consists of more than just a large building project and can encompass small projects as well. No matter what the size of your project, you need to have some sort of project management. How you manage your project has everything to do with its outcome.