Carlos Matos
Carlos Matos

Reputation: 29

Copy TByteDynArray (array of byte) to string

How can I copy contents of a TByteDynArray variable to a string variable or even better, to a TMemoryStream?

Remy, thanks for your answer.

Well, I can't get it to work. I'm doing this: obtReferenciaPagamentoResponse.pdf is a TByteDynArray (array of byte) that comes throught a WebService call, that is referenced on the XSD like xsd:base64Binary.

procedure saveFile;
var
  LInput, LOutput: TMemoryStream;
  Id: Integer;
  Buff: AnsiString;
  //Buff: String;
begin
  LInput := TMemoryStream.Create;
  LOutput := TMemoryStream.Create;

  // Tried like this also
  //SetLength(Buff, Length(obtReferenciaPagamentoResponse.pdf));
  //Move(obtReferenciaPagamentoResponse.pdf[0], Buff[1],       Length(obtReferenciaPagamentoResponse.pdf));

  // Tried other charsets
  Buff := TEncoding.Ansi.GetString(obtReferenciaPagamentoResponse.pdf);

  LInput.Write(Buff[1], Length(Buff) * SizeOf(Buff[1]));
  LInput.Position := 0;

  TNetEncoding.Base64.Decode(LInput, LOutput);
  LOutput.Position := 0;
  LOutput.SaveToFile(SaveDialog2.FileName);

  LInput.Free;
  LOutput.Free;
end;

But the PDF file is saved incompleted, I guess, because is always corrupted on open. What am I doing wrong?

Upvotes: 0

Views: 344

Answers (1)

Remy Lebeau
Remy Lebeau

Reputation: 596352

String is an alias for UnicodeString since 2009. As UnicodeString characters are now encoded in UTF-16, it does not make sense to copy raw bytes into a (Unicode)String unless the bytes are also encoded in UTF-16. In that case, you can simply use SetLength() to allocate the String's length to the appropriate number of Chars and then Move() the raw bytes into the String's allocated memory. Otherwise, use TEncoding.GetString() instead to decode the bytes into a UTF-16 String using the appropriate charset.

As for TMemoyStream, it has a Write() method for writing raw bytes into the stream. Simply set its Position property to the desired offset and then write the bytes.

Upvotes: 1

Related Questions