使用MemoryStream写入大文件时出现OutOfMemory异常

时间:2020-01-13 17:31:32

标签: c# memory

我正在尝试使用MemoryStream保存一个大文件(〜2GB)。我的服务器有大约6-8GB的RAM,但是即使将文件加载到MemoryStream对象时,也会收到OutOfMemoryException。我需要将文件以字节数组的形式加载以在其上运行防病毒进程,因此无法对它进行分块。

当前,我以这种方式加载字节数组:

    public static byte[] ReadBytes(this Stream inputStream)
    {
        if (inputStream == null)
        {
            return new byte[0];
        }

        if (inputStream.CanSeek && inputStream.Position > 0)
        {
            inputStream.Position = 0;
        }

        // Load by 16KB chunks
        var buffer = new byte[16 * 1024];

        using (var ms = new MemoryStream())
        {
            int read;
            while ((read = inputStream.Read(buffer, 0, buffer.Length)) > 0)
            {
                ms.Write(buffer, 0, read);
            }
            if (inputStream.CanSeek) inputStream.Position = 0;
            return ms.ToArray();
        }
    }

有什么办法可以避免这个错误?

谢谢。

0 个答案:

没有答案
相关问题