All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.sonar.l10n.delphi.rules.community-delphi.UnicodeToAnsiCast.html Maven / Gradle / Ivy

There is a newer version: 1.12.1
Show newest version

Why is this an issue?

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.

How to fix it

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.

Resources





© 2015 - 2024 Weber Informatics LLC | Privacy Policy