在Oxygene中流到字节数组转换

时间:2013-05-09 23:42:38

标签: .net oxygene

我正在尝试使用这个传统的Delphi Prism应用程序找到出路。我之前从未参与过Delphi Prism。

如何将Stream类型转换为Byte Array类型?由于我不了解Delphi Prism,所以请详细阅读代码。

基本上我想使用WCF服务上传一个Image,并希望将Image数据作为字节数组传递。

感谢。

2 个答案:

答案 0 :(得分:3)

选项1)如果您使用的是MemoryStream,则可以直接使用MemoryStream.ToArray方法。

选项2)如果您使用的是.Net 4,请使用CopyTo方法将源Stream的内容复制到MemoryStream并调用MemoryStream.ToArray函数。

喜欢这样

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

选项3)您正在使用.Net的旧版本,您可以编写自定义函数以从源流中提取数据,然后填写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;

答案 1 :(得分:2)

以下是使用文件流的示例(但这适用于任何类型的流):

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;

在第一行我创建了一个文件流,这可以是你的流。 然后我用流的长度创建一个byte数组。 在第三行,我将流的内容复制到字节数组中。

相关问题