2

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.

marc hoffman
  • 586
  • 1
  • 5
  • 14
Asker
  • 23
  • 3

2 Answers2

3

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;
RRUZ
  • 134,889
  • 20
  • 356
  • 483
  • I am using VS2008 and I guess .Net version is .Net 2.0. I was trying to convert System.IO.Stream to MemoryStream using your solution - AStream.CopyTo(LStream), but Astream does not have the CopyTo method. AStream := new Stream(); AStream := HtmlInputFile_UploadPath.PostedFile.InputStream; – Asker May 10 '13 at 01:08
2

Here is an example using a filestream (but this should work on any kind of stream):

class method ConsoleApp.Main;
begin
  var fs := new FileStream('SomeFileName.dat', FileMode.Open);
  var buffer := new Byte[fs.Length];
  fs.Read(buffer, 0, fs.Length);
end;

On the first line I create a file stream to start with, this can be your stream. Then I create an array of byte with the length of the stream. on the third line I copy the contents of the stream into the byte array.

  • Actually, no. You are writing the (empty) buffer variable to the stream. You should use fs.Read instead... – HeartWare May 10 '13 at 07:53