读取文件到数组时出错

时间:2011-10-04 18:18:06

标签: 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

1 个答案:

答案 0 :(得分:12)

在第一次迭代中,您正在调用

fs.Read(_FileName, 0, 1024);

没关系(虽然你在Convert.ToInt32上呼叫int,但我不知道。)

在第二次迭代中,您将调用

fs.Read(_FileName, position, 2048);

尝试读入从_FileName开始的position字节数组(非零)并获取最多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);
    }
}
相关问题