2009-11-19 29 views
2

任何人都可以在這裏看到我的邏輯中的任何明顯的漏洞。基本上,我需要在發送之前分手的字節數組到10000塊:組塊流。代碼是否正確?需要第二組眼睛

byte [] bytes = GetLargePieceOfData();  
Stream stream = CreateAStream(); 

if (bytes.Length > 10000) 
{ 
    int pos = 0; 
    int chunkSize = 10000; 

    while (pos < bytes.Length) 
    { 
     if (pos + chunkSize > bytes.Length) 
      chunkSize = bytes.Length - pos; 

     stream.Write(bytes, pos, chunkSize); 
     pos += chunkSize; 
    } 
} 
else 
{ 
    stream.Write(bytes, 0, bytes.Length); 
} 
+0

不,看起來一目瞭然。 – leppie 2009-11-19 06:53:15

+0

我認爲,它工作正常 – 2009-11-19 06:54:00

回答

4

一切似乎是爲了,但最外層的if語句實在是多餘的,如下面的代碼

int pos = 0; 
int chunkSize = 10000; 

while (pos < bytes.Length) 
{ 
    if (pos + chunkSize > bytes.Length) 
     chunkSize = bytes.Length - pos; 

    stream.Write(bytes, pos, chunkSize); 
    pos += chunkSize; 
} 

也將處理數組小於塊大小的情況。

+0

你有一個好點。 – AngryHacker 2009-11-19 07:07:20