【问题标题】:Convert Stream to byte[] c# for large files of 2GB将 Stream 转换为 byte[] c# 用于 2GB 的大文件
【发布时间】:2017-09-29 21:54:07
【问题描述】:

尝试将 Stream 对象转换为 byte[] 并使用以下方法:

public static byte[] ReadFully(System.IO.Stream input)
{
            byte[] buffer = new byte[16*1024];
            using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
            {
                int read;
                while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
                {
                    ms.Write(buffer, 0, read);
                }
                return ms.ToArray();
            }
}

但是,输入参数“input”用于 2 GB 的大文件,因此代码不会进入 while 循环,因此不会将其转换为字节数组。

对于较小的文件,它工作正常

【问题讨论】:

  • 我怀疑您将很难创建一个包含超过 2^31 个元素的数组。为什么需要这样做?
  • 尝试使用 sharepoint 2010 - 客户端对象模型下载大文件。我们有2GB的文件。所以要下载它,我们使用了以下代码:FileInformation fileInfo = Microsoft.SharePoint.Client.File.OpenBinaryDirect(clientContext, "thisFile"); System.IO.Stream 流 = fileInfo.Stream;现在我们的项目要求是我们要返回 byte[] 而不是 Stream 对象,因此尝试将 stream 转换为 byte[]
  • 老实说,“项目要求”听起来很啰嗦。你检查过这么大的字节数组是否可行?
  • 是的,验证了字节数组在 2 gb 之前是可行的
  • 但是“直到”2GB 已经很好了......超过 2GB 怎么样?您是否尝试过创建 3GB 字节数组?

标签: c# stream byte


【解决方案1】:

这就是Stream 的用途。 您不会将整个内容加载到 byte[] 中,而是从 Stream 读取一个小缓冲区到内存中并处理它,然后处理并读取下一个缓冲区。

如果还需要使用字节[]:

您的应用似乎无法处理超过2^32 Bytes 内存,这意味着它是32 位。 尝试将其更改为 64bit(在 Project Properties 中转到 Build 并禁用 Prefer 32 bit

【讨论】:

  • 将程序更改为Prefer 32 bit 不会使您的程序成为 64 位,它只是意味着您在 64 位操作系统上使用 64 位。该程序在 32 位操作系统上仍然会失败。您需要做的是从 AnyCPU 更改为 x64,这样程序就无法在 32 位上运行。
  • 我们以file.Stream的形式从SharePoint获取数据。我们的要求是在 byte[] 中获取流的内容。由于我们的项目接口返回字节数组数据。如果还有其他简单的方法,请帮忙
【解决方案2】:

对象限制在 32 位以下。 (这就是为什么所有索引都使用 int)

如何使用包含字节数组的列表来处理整个数据?

    public List<byte[]> ReadBytesList(string fileName)
    {
        List<byte[]> rawDataBytes= new List<byte[]>();
        byte[] buff;
        FileStream fs = new FileStream(fileName,
                                       FileMode.Open,
                                       FileAccess.Read);
        BinaryReader br = new BinaryReader(fs);
        long numBytes = new FileInfo(fileName).Length;
        int arrayCount= (int)(numBytes / 2100000000); //2147483648 is max
        int arrayRest = (int)(numBytes % 2100000000);
        if(arrayCount>0)
        {
            for (int i = 0; i < arrayCount; i++)
            {
                buff = br.ReadBytes(2100000000);
                rawDataBytes.Add(buff);
            }
            buff = br.ReadBytes(arrayRest);
            rawDataBytes.Add(buff);
        }
        else
        {
            buff = br.ReadBytes(arrayRest);
            rawDataBytes.Add(buff);
        }
        return rawDataBytes;
    }

【讨论】:

    猜你喜欢
    • 2019-05-01
    • 2018-01-15
    • 2021-12-05
    • 1970-01-01
    • 2023-03-15
    • 1970-01-01
    • 1970-01-01
    • 2020-02-03
    • 1970-01-01
    相关资源
    最近更新 更多