c# - Why can I upload a file, but not download it without getting an Out of Memory Exception? -
c# - Why can I upload a file, but not download it without getting an Out of Memory Exception? -
my software has feature allows users upload files stored byte strings in database. code works this:
the number of bytes in file calculated, , byte array created has length. file read byte array. here, file split pieces , stored in database. done using next code:
openfile1 = new filestream(filepath, filemode.open, fileaccess.read, fileshare.read); blah, blah, blah . . . openfilebytesnumber = openfile1.length; bytearray = new byte[openfilebytesnumber]; openfile1.read(bytearray, 0, (int)(openfilebytesnumber)); fullbytestring = convert.tobase64string(bytearray);
when download it, next happens:
a byte string created loading file info database , concatenating pieces. string set byte array using next line of code:
bytearray = convert.frombase64string(bytestring.tostring());
this out of memory exception. why getting outofmemoryexception on download, not upload?
base64 has 30% overhead, , strings have 100% overhead (as char
16 bits). makes 160% overhead (1.3 * 2.0 = 2.6) keeping info base64 string in memory.
you keeping info in dataset
in memory, along stringbuilder
, along final string, along final result. that's total overhead of 780% (3 * 2.6 + 1 = 8.8).
the code requires 9 times much memory file size.
to cut down memory usage can:
use info reader instead of info set. way have 1 record @ time in memory. do conversion base64 bytes on each record instead of building whole string. can done if string length evenly divisable four.side note: using read
method wrong when reading file. read
method returns number of bytes read, may smaller number of bytes requested. need homecoming value method , repeat phone call until have data:
int openfilebytesnumber = (int)openfile1.length; int len = 0; while (len < openfilebytesnumber) { int l = openfile1.read(bytearray, len, openfilebytesnumber - len); if (l == 0) { // unexpended end of file error - improve handle } len += l: }
c# .net file exception out-of-memory
Comments
Post a Comment