Share via


Convert.ToBase64String throws 'System.OutOfMemoryException' for byte [] size of 365151415

Question

Tuesday, April 15, 2008 11:35 AM

 i am trying to convert byte[] to base64string format so that i can send that information to third party...

i am doing like this to get the base64String.....

1. first getting the Byte[] and then calling  Convert.ToBase64String(byte[] para)

it is working fine all the files except 2-3 (those files are 350MB in size) and it is failing while executing this function: Convert.ToBase64String(byte[] para)

is there any constraint on Convert.ToBase64String like i cannot use for large byte size?? if so what are the other alternative ways for doing this...???

 

thanks a lot in advance 

All replies (4)

Tuesday, April 15, 2008 12:12 PM âś…Answered

is there any constraint on Convert.ToBase64String

Yes. Virtual memory. It sort of says so in the message.... OutOfMemoryException. That means that the constraint available memory has been violated. Memory is not an infinite resource. Large, but not infinite.

other alternative ways

First, don't even think about loading 350Mb of data into a byte[] !!!

Do it in chunks. Read the data in chunks of data a multiple of 3 bytes in length, I'd suggest less than 85Kb in length and convert each chunk separately and write them in converted chunks. Base64 encoding will encode 3 bytes into 4 bytes of text, it's ok to concatenate chunks. Only the last one which may be not a multiple of 3 may contain padding in the converted output.


Tuesday, April 15, 2008 2:27 PM

 thanks for responding to this query.

i am trying to do like this by reading in chucks but still getting same error....could you tell me whether i am doing in a right way?? or else am i missing anything??

FileStream fs = new FileStream(docPath, FileMode.Open, FileAccess.Read);
Byte[] obj = new Byte[fs.Length];
          fs.Read(obj, 0, (Int32)fs.Length);

                String strImage = String.Empty;
                for (Int32 i = 0; i < obj.Length; i = i + 3072)
                {
                    strImage += Convert.ToBase64String(obj, 0, i);
                }


Tuesday, April 15, 2008 2:33 PM

reading in chucks

You need to read and write in chunks, i.e. read a chunk, convert, write a chunk, loop back, read a chunk, convert, write a chunk, ..., etc until done. Now you're just making it even worse by building a super super super huge string - which will require even more memory...


Tuesday, August 23, 2011 6:05 AM

Just in case some one is looking for the solution to this problem, see this thread:

http://forums.asp.net/t/1662571.aspx/1?URGENT+Exception+OutOfMemoryException+thrown+when+when+converting+to+String+

Tarek.