2011-10-04 48 views
6

我爬循環的第二次迭代以下錯誤:
Offset and length were out of bounds for the array or count is greater than the number of elements from index to the end of the source collection.讀取文件錯誤到數組

,這是我的循環

FileStream fs = new FileStream("D:\\06.Total Eclipse Of The Moon.mp3", FileMode.Open); 

    byte[] _FileName = new byte[1024]; 
    long _FileLengh = fs.Length; 

    int position = 0; 

    for (int i = 1024; i < fs.Length; i += 1024) 
    { 
     fs.Read(_FileName, position, Convert.ToInt32(i)); 

     sck.Client.Send(_FileName); 
     Thread.Sleep(30); 

     long unsend = _FileLengh - position; 

     if (unsend < 1024) 
     { 
      position += (int)unsend; 
     } 
     else 
     { 
      position += i; 
     } 
    } 
    fs.Close(); 
} 

fs.Length = 5505214 

回答

12

在第一次迭代,你打電話

fs.Read(_FileName, 0, 1024); 

這很好(但你爲什麼要上int調用Convert.ToInt32,我不知道知道了。)

在第二次迭代,你要打電話

fs.Read(_FileName, position, 2048); 

正試圖讀入_FileName字節數組開始position(這是非零)和取入2048字節。字節數組只有1024個字節長,所以不可能可能工作。

其他問題:

  • 您沒有使用using聲明,等等例外,你會離開流開
  • 你無視Read的返回值,這意味着你不t知道您的緩衝區有多少實際上已被讀取
  • 您無條件地將套接字發送到完整的緩衝區,而不管已經讀了多少。

你的代碼也許應該看起來更像是這樣的:

using (FileStream fs = File.OpenRead("D:\\06.Total Eclipse Of The Moon.mp3")) 
{ 
    byte[] buffer = new byte[1024]; 
    int bytesRead; 
    while ((bytesRead = fs.Read(buffer, 0, buffer.Length)) > 0) 
    { 
     sck.Client.Send(buffer, 0, bytesRead); 
     // Do you really need this? 
     Thread.Sleep(30); 
    } 
} 
+0

fs.Read(_filename,位置,2048); << position = 1024,2048 - 1024 = 1024所以我的_FileName = 1024有足夠的空間 –

+1

@Acid:但是你說你想開始讀取_FileName的索引1024。有*是*沒有這樣的索引 - 數組的最後一個索引是1023.請閱讀'Stream.Read'的文檔 - 我不認爲你明白第二個和第三個參數是什麼。 –

+1

最後一句話實際上讓我注意到我錯誤地解釋了'offset'參數。認爲它與源流有關,而不是緩衝區。幫助我修復一個重要的bug,謝謝! – wodzu