maxfax
maxfax

Reputation: 4315

How do I load a Unicode string into a TTreeView via a TMemoryStream?

I need to do something with a Unicode string of a tree of a TTreeView, so I want to load this string into a memory stream and then load the memory stream into the tree view. How can I do this?

Upvotes: 2

Views: 1531

Answers (1)

Arnaud Bouchez
Arnaud Bouchez

Reputation: 43053

You be tempted to use directly the TStringStream class intead of a TMemoryStream. But this TStringStream class will encode the UnicodeString into an AnsiString before storage, in the Unicode Delphi version...

So here are some functions to create a TMemoryStream instance with pure Unicode content, then retrieve back this text:

function StringToMemoryStream(const Text: string): TMemoryStream;
var Bytes: integer;
begin
  if Text='' then 
    result := nil else
  begin
    result := TMemoryStream.Create;
    Bytes := length(Text)*sizeof(Char);
    result.Size := Bytes;
    move(pointer(Text)^,result.Memory^,Bytes);
  end;
end;

function MemoryStreamToString(MS: TMemoryStream): string;
begin
  if MS=nil then
    result := '' else
    SetString(result,PChar(MS.Memory),MS.Size div sizeof(Char));
end;

Be sure that you Free the TMemoryStream when you won't need it any more.

By using sizeof(Char) and PChar, this code will also work with previous non-Unicode version of Delphi.

Upvotes: 1

Related Questions