我有下面的代碼從流中讀取數據(在這種情況下,從命名管道),併成一個字節數組:在.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似乎有點混亂。謝謝!
這讀取到流的末尾,但意圖是隻讀直到「IsMessageComplete」。 – 2010-06-18 12:34:47
感謝您的文章鏈接;它看起來像我正在做幾乎相同的算法,但在循環中具有不同的終止條件。 – 2010-06-18 12:40:56
謝謝。它幫助我解決我的問題。 – nvtthang 2012-11-06 04:04:05