将tif文件转换为base64编码时出现OutOfMemory异常

时间:2020-08-07 13:59:26

标签: c# out-of-memory tobase64string large-file-upload

我们已经在C#中创建了控制台应用程序,它将读取多页tif / tiff文件,按页面拆分,然后转换为base64编码以在其他目标应用程序中上传文件(因为该文件仅接受base64编码来上传文档)并且只要文件大小超过500 MB,就会引发“内存不足”异常

Exception at System.Convert.ToBase64String(Byte[] inArray, Int32 offset, Int32 length, Base64FormattingOptions options)
   at System.Convert.ToBase64String(Byte[] inArray)

代码段:

Byte[] bytes = File.ReadAllBytes(filepath);
String base64stringofdocument = Convert.ToBase64String(bytes);

文件路径参考>文件的绝对路径

1 个答案:

答案 0 :(得分:1)

使用字符串会涉及开销。对于大量数据,最好使用数组或流。在这种情况下,您可以首先重写代码以使用Convert.ToBase64CharArray。因此,您的代码将变为如下所示:

Byte[] bytes = File.ReadAllBytes(filePath);
// Compute the number of Base64 converted characters required (must be divisible by 4)
long charsRequired = (long)((4.0d/3.0d) * bytes.Length);
if (charsRequired % 4 != 0) {
    charsRequired += 4 - charsRequired % 4;
}
// Allocate buffer for characters, and write converted data into the array
Char[] chars = new Char[charsRequired];
Convert.ToBase64CharArray(bytes, 0, bytes.Length, chars, 0);

然后,您可以将chars数组上载到目标应用程序。