Convert a VERY LARGE binary file into a Base64String incrementally

后端 未结 3 1357
旧时难觅i
旧时难觅i 2021-01-04 19:25

I need help converting a VERY LARGE binary file (ZIP file) to a Base64String and back again. The files are too large to be loaded into memory all at once (they throw OutOfMe

3条回答
  •  北海茫月
    2021-01-04 20:12

    You can avoid using a secondary buffer by passing offset and length to Convert.ToBase64String, like this:

    private void ConvertLargeFile()
    {
        using (var inputStream  = new FileStream("C:\\Users\\test\\Desktop\\my.zip", FileMode.Open, FileAccess.Read)) 
        {
            byte[] buffer = new byte[MultipleOfThree];
            int bytesRead = inputStream.Read(buffer, 0, buffer.Length);
            while(bytesRead > 0)
            {
                String base64String = Convert.ToBase64String(buffer, 0, bytesRead);
                File.AppendAllText("C:\\Users\\test\\Desktop\\Base64Zip", base64String); 
                bytesRead = inputStream.Read(buffer, 0, buffer.Length);           
            }
        }
    }
    

    The above should work, but I think Rene's answer is actually the better solution.

提交回复
热议问题