Casting a Unicode type like String to an ANSI type like AnsiString can
lead to data loss. Because any given ANSI code page contains only a small subset of Unicode
characters, converting a Unicode type to ANSI will cause all non-ANSI characters to be replaced
with question marks.
Code that casts Unicode types directly to ANSI types are generally problematic on a design level. As such, there is no single solution.
If you are casting to AnsiString to get the string as bytes, consider using
TEncoding.GetBytes to convert the contents of the string into bytes using a specific
encoding:
procedure WriteToFile(MyStr: string);
var
MyAnsiStr: AnsiString;
MyStream: TFileStream;
begin
MyAnsiStr := AnsiString(MyStr);
MyStream := TFileStream.Create('myfile.txt');
try
MyStream.WriteBuffer(MyAnsiStr[1], Length(MyAnsiStr));
finally
FreeAndNil(MyStream);
end;
end;
procedure WriteToFile(MyStr: string);
var
MyBytes: TBytes;
MyStream: TFileStream;
begin
MyBytes := TEncoding.ANSI.GetBytes(MyStr);
MyStream := TFileStream.Create('myfile.txt');
try
MyStream.WriteBuffer(MyBytes, Length(MyBytes));
finally
FreeAndNil(MyStream);
end;
end;
If you are casting to AnsiString to pass to a WinAPI routine, use a
WideString overload instead.