.netoxygene

Stream to Byte array conversion in Oxygene


I'm trying to find a way out with this legacy Delphi Prism application. I have never worked on Delphi Prism before.

How do I convert a Stream type to Byte Array type? Please detailed code will be really appreciated as I have no knowledge of Delphi Prism.

Basically I want to upload an Image using WCF service and want to pass the Image data as byte array.

Thanks.


Solution

  • Option 1) If you are using a MemoryStream you can use the MemoryStream.ToArray Method directly.

    Option 2) If you Are using .Net 4, copy the content of the source Stream using the CopyTo method to a MemoryStream and the call the MemoryStream.ToArray function.

    like so

    method TMyClass.StreamToByteArr(AStream: Stream): array of Byte;
    begin
        using LStream: MemoryStream := new MemoryStream() do 
        begin
          AStream.CopyTo(LStream);
          exit(LStream.ToArray());
        end
    end;
    

    option 3) you are using a old verison of .Net, you can write a custom function to extract the data from the source stream and then fill a MemoryStream

    method TMyClass.StreamToByteArr(AStream: Stream): array of Byte;
    var 
      LBuffer: array of System.Byte;
      rbytes: System.Int32:=0;
    begin
      LBuffer:=new System.Byte[1024];
      using LStream: MemoryStream := new MemoryStream() do 
      begin
        while true do 
        begin
          rbytes := AStream.Read(LBuffer, 0, LBuffer.Length);
          if rbytes>0 then
            LStream.Write(LBuffer, 0, rbytes)
          else
            break;
        end;
        exit(LStream.ToArray());
       end;
    end;