2010-06-18 19 views
13

我有下面的代碼從流中讀取數據(在這種情況下,從命名管道),併成一個字節數組:在.NET中將Stream(未知長度)轉換爲字節數組的最佳方法?

// NPSS is an instance of NamedPipeServerStream 

int BytesRead; 
byte[] StreamBuffer = new byte[BUFFER_SIZE]; // size defined elsewhere (less than total possible message size, though) 
MemoryStream MessageStream = new MemoryStream(); 

do 
{ 
    BytesRead = NPSS.Read(StreamBuffer, 0, StreamBuffer.Length); 
    MessageStream.Write(StreamBuffer, 0, BytesRead); 
} while (!NPSS.IsMessageComplete); 

byte[] Message = MessageStream.ToArray(); // final data 

可否請你看看,讓我知道,如果它可以做得更有效率還是整潔?使用MemoryStream似乎有點混亂。謝謝!

回答

18

無恥地從Jon Skeet's article複製。

public static byte[] ReadFully (Stream stream) 
{ 
    byte[] buffer = new byte[32768]; 
    using (MemoryStream ms = new MemoryStream()) 
    { 
     while (true) 
     { 
      int read = stream.Read (buffer, 0, buffer.Length); 
      if (read <= 0) 
       return ms.ToArray(); 
      ms.Write (buffer, 0, read); 
     } 
    } 
} 
+1

這讀取到流的末尾,但意圖是隻讀直到「IsMessageComplete」。 – 2010-06-18 12:34:47

+1

感謝您的文章鏈接;它看起來像我正在做幾乎相同的算法,但在循環中具有不同的終止條件。 – 2010-06-18 12:40:56

+1

謝謝。它幫助我解決我的問題。 – nvtthang 2012-11-06 04:04:05

0

看起來您目前的解決方案非常好。如果您希望代碼看起來更乾淨,您可以考慮將其包含在擴展方法中。

+0

有趣的是,我從來沒有聽說過你的文章之前的擴展方法。感謝提示和查看我的代碼 – 2010-06-18 12:42:58

3
int read = stream.Read (buffer, 0, buffer.Length); 

如果沒有數據可用,此行將永遠阻止。 Read是一個阻塞函數,它會阻塞線程,直到它讀取至少一個字節,但如果沒有數據,則永久阻塞。

+0

@ derek-beattie我怎麼能產生這個問題? – 2016-02-21 23:08:45

+0

@IvandroIsmael abhinaw回答了這個問題 – 2016-02-22 19:56:45

+0

Ohw,對不起,夥伴Derek-Beattie。/cc @abhinaw – 2016-02-22 20:01:26

相關問題