Search code examples
unicodedelphi-7

Delphi 7: No second parameter in TStrings.SaveToFile() method


I need to make changes to an old legacy project in Delphi 7.

I need to save a TStringList to a file with Unicode encoding. All resources I have found describe a second parameter for specifying an encoding in the SaveToFile()/LoadFromFile() methods, but there is no such parameter in Delphi 7. It was probably added in later versions.

How can I save UTF-8 text to a file (.csv) in Delphi 7?


Solution

  • The parameter you are looking for was introduced in Delphi 2009, when Delphi's String type migrated from AnsiString to UnicodeString.

    Prior to Delphi 2009, you will have to encode the TStringList entries to UTF-8 yourself. You can put UTF-8 data in an AnsiString (UTF8String in those versions was just an alias for AnsiString), and TStringList will save the data as-is.

    However, you may be tempted to use the RTL's UTF8Encode() function, but know that prior to Delphi 2009 it doesn't support Unicode codepoints above U+FFFF. If you need to handle codepoints that high, you will have to use Microsoft's MultiByteToWideChar() function instead.