读取文件错误到数组

问题描述:

我爬循环的第二次迭代以下错误:
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 

在第一次迭代,你打电话

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);

+1

@Acid:但是你说你想开始读取_FileName的索引1024。有*是*没有这样的索引 - 数组的最后一个索引是1023.请阅读'Stream.Read'的文档 - 我不认为你明白第二个和第三个参数是什么。 –

+1

最后一句话实际上让我注意到我错误地解释了'offset'参数。认为它与源流有关,而不是缓冲区。帮助我修复一个重要的bug,谢谢! – wodzu