读取文件到数组时出错

本文关键字:出错 数组 文件 读取 | 更新日期: 2023-09-27 18:10:29

在循环的第二次迭代时,我得到了以下错误:
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);

试图从position(非零)开始读入_FileName字节数组并获取最多2048个字节。字节数组只有1024字节长,所以可能无法工作。

额外的问题:

  • 你没有使用using语句,所以在异常情况下你会让流打开
  • 你忽略了Read的返回值,这意味着你不知道你的缓冲区有多少实际上被读取
  • 无条件地向套接字发送完整的缓冲区,不管已经读取了多少。

你的代码应该看起来更像这样:

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