读取文件到数组时出错

Ira*_*ili 6 c# filestream

我在循环的第二次迭代中得到以下错误:
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
Run Code Online (Sandbox Code Playgroud)

Jon*_*eet 12

在第一次迭代中,你正在打电话

fs.Read(_FileName, 0, 1024);
Run Code Online (Sandbox Code Playgroud)

这很好(但你为什么要叫Convert.ToInt32int,我不知道.)

在第二次迭代中,您将要打电话

fs.Read(_FileName, position, 2048);
Run Code Online (Sandbox Code Playgroud)

它试图读入_FileNameposition(非零)开始的字节数组并获取最多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);
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 最后一句话实际上让我注意到我误解了“offset”参数。认为这与源流有关,而不是缓冲区。帮助我修复了一个严重的错误,谢谢! (2认同)