2009-02-22 60 views

回答

3

我不知道他們爲什麼這樣做,但它不是一般的一個很好的例子 - 例如,他們正在使用顯式調用的FileStream而是採用了using聲明,並假設以Read單一的通話將讀取整個文件的Close(不是在finally塊)。哎呀,即使將整個文件讀入緩衝區也是一個糟糕的主意 - 最好是一次將塊複製到DeflateStream

這些東西表明,我認爲這是不值得擔心這個例子中的代碼,這個特定的奇數位(額外的100個字節)。當然不要把它視爲「最佳實踐」。

MSDN的例子通常比這更好的 - 雖然有很多其他奇怪的人的。

編輯:已經重新讀取代碼和CodeMelt的答案,它確實需要額外的100個字節 - 但僅僅是因爲ReadAllBytesFromStream實現如此糟糕。這裏有一個更好的實現,它總是詢問流填充緩衝區的其餘部分:

public static int ReadAllBytesFromStream(Stream stream, byte[] buffer) 
{ 
    int offset = 0; 
    int bytesRead; 
    while ((bytesRead = stream.Read(buffer, offset, 
            buffer.Length-offset)) > 0) 
    { 
     offset += bytesRead; 
    } 
    return offset; 
} 

(請注意,有沒有必要都offsettotalCount,因爲他們總是有相同的值。)

+0

我完全同意你關於你的關閉點和完全讀取所有字節。我只是想確認解壓縮緩衝區是否與原始緩衝區的長度相同,在實踐中不需要分配100字節或更多? – George2 2009-02-22 12:26:54

+0

以前的實施代碼在哪些情況下會有問題?你能告訴我一個例子嗎? – George2 2009-02-22 14:13:38

2

它防止stream.Read(buffer,offset,100)在下面的方法中超過其長度,因爲該流會一直讀取,直到它不讀取任何內容。

public static int ReadAllBytesFromStream(Stream stream, byte[] buffer) 
{ 
// Use this method is used to read all bytes from a stream. 
int offset = 0; 
int totalCount = 0; 
    while (true) 
    { 
    // even it reads to the end, but it will still read the next 
    // 100 bytes to see if anything has been read. 
    int bytesRead = stream.Read(buffer, offset, 100); 
     if (bytesRead == 0) 
     { 
     break; 
     } 
offset += bytesRead; 
totalCount += bytesRead; 
    } 
return totalCount; 
}