Reputation: 23
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.
Upvotes: 2
Views: 1652
Reputation: 242
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.
Upvotes: 2
Reputation: 136381
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;
Upvotes: 3