I'm trying to save a large file (~2GB) using MemoryStream
. My server has around 6-8GB of RAM, but even then when I load the file to a MemoryStream object, I get an OutOfMemoryException. I need the file loaded as a byte array to run an anti-virus process on it, so there's no option to chunk it.
Currently I'm loading the byte array this way:
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();
}
}
Is there something I can do to avoid this error?
Thank you.