AnsiString To Stream
ansistring, delphi, delphi-xe2, stream
Solution
In D2009+, `TStringStream` expects a `UnicodeString`, not an `AnsiString`. If you just want to write the contents of the `AnsiString` as-is without having to convert the data to Unicode and then back to Ansi, use `TMemoryStream` instead:
function AnsiStringToStream(const AString: AnsiString): TStream;
begin
Result := TMemoryStream.Create;
Result.Write(PAnsiChar(AString)^, Length(AString));
Result.Position := 0;
end;
Since `AnsiString` is codepage-aware in D2009+, ANY string that is passed to your function will be forced to the OS default Ansi encoding. If you want to be able to pass any 8-bit string type, such as `UTF8String`, without converting the data at all, use `RawByteString` instead of `AnsiString`:
function AnsiStringToStream(const AString: RawByteString): TStream;
begin
Result := TMemoryStream.Create;
Result.Write(PAnsiChar(AString)^, Length(AString));
Result.Position := 0;
end;
Problem
I created the following code: ``` Function AnsiStringToStream(Const AString: AnsiString): TStream; Begin Result := TStringStream.Create(AString, TEncoding.ANSI); End; ``` But I'm "W1057 Implicit string cast from 'AnsiString' to 'string'" There is something wrong with him? Thank you.