【问题标题】:Error reading file into array将文件读入数组时出错
【发布时间】:2023-04-04 09:26:01
【问题描述】:

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

【问题讨论】:

    标签: c# filestream


    【解决方案1】:

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

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

    【讨论】:

    • fs.Read(_FileName, position, 2048);
    • @Acid:但是你说你想从_FileName的索引1024开始阅读。 没有没有这样的索引 - 数组的最后一个索引是 1023。请阅读Stream.Read 的文档 - 我认为你不明白第二个和第三个参数的用途。跨度>
    • 最后一句话实际上让我注意到我误解了offset参数。认为它与源流有关,而不是缓冲区。帮助我修复了一个严重的错误,谢谢!
    猜你喜欢
    • 1970-01-01
    • 2021-07-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多