2013-05-09 36 views
2

我試圖找到一個與這個傳統的Delphi Prism應用程序的出路。之前我從來沒有在Delphi Prism上工作過。流到Oxygene的字節數組轉換

如何將Stream類型轉換爲Byte數組類型?請詳細的代碼將真正讚賞,因爲我不知道德爾菲棱鏡。

基本上我想上傳一個使用WCF服務的圖像,並希望將圖像數據作爲字節數組傳遞。

謝謝。

回答

3

選項1)如果您使用的是MemoryStream,則可以直接使用MemoryStream.ToArray方法。

選項2)如果您使用的是.Net 4,請使用CopyTo方法將源流的內容複製到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)使用的是淨的老verison,可以編寫自定義函數來從所述源流中提取的數據,然後填充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; 
+0

我使用VS2008,我猜.Net版本是.Net 2.0。 我試圖將System.IO.Stream轉換爲MemoryStream使用您的解決方案 - AStream.CopyTo(LStream),但Astream沒有CopyTo方法。 AStream:= new Stream(); AStream:= HtmlInputFile_UploadPath.PostedFile.InputStream; – Asker 2013-05-10 01:08:32

+0

檢查更新 – RRUZ 2013-05-10 01:20:50

2

下面是一個使用FILESTREAM一個例子(但應在任何類型的流的工作):

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; 

在第一行我創建了一個文件流開始,這可以是你的流。 然後我用流的長度創建一個字節數組。 在第三行我將流的內容複製到字節數組中。

+0

其實,沒有。您正在將(空)緩衝區變量寫入流中。你應該使用fs.Read來代替... – HeartWare 2013-05-10 07:53:20

+0

固定!謝謝。 – JeroenVandezande 2013-05-10 07:56:27

+0

謝謝。這也適用。 – Asker 2013-05-13 01:06:24