简体   繁体   中英

Convert large httppostedfilebase to byte[]

I want to convert httppostedfilebase type to byte[] type. I use this code :

    private static byte[] ConverToBytes(HttpPostedFileBase file)
    {
        int fileSizeInBytes = file.ContentLength; //134675091 (129MB)
        MemoryStream target = new MemoryStream();
        file.InputStream.CopyTo(target);//System.OutOfMemoryException
        byte[] data = target.ToArray();

        return data;
    }

When I use this code, I get the System.OutOfMemoryException.

any soulotion about it

Actually you may creating more than one copy of byte stream with MemoryStream , this is why OutOfMemoryException was thrown. Use BinaryReader instead:

private static byte[] ConvertToBytes(HttpPostedFileBase file)
{
    int fileSizeInBytes = file.ContentLength;
    byte[] data = null;
    using (var br = new BinaryReader(file.InputStream))
    {
        data = br.ReadBytes(fileSizeInBytes);
    }

    return data;
}

NB: I strongly suggests using statement wraps all instance creation which uses memory space and implements IDisposable such like MemoryStream does.

Similar issue:

Convert HttpPostedFileBase to byte[] array

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM