Encode in base 64 file C #

0

Hi, I'm coding a file in base 64 in c #, but for large files it does not work anymore.

char[] base64 = new char[miArchivo.Length];
Convert.ToBase64CharArray(miArchivo, 0, miArchivo.Length, base64, 0);
return Encoding.ASCII.GetBytes(base64);

I've tried it with MemoryStream but it has not worked, the problem is in the size of the char [] that in base64 takes more I think.

    
asked by jooooooooota 03.07.2017 в 13:02
source

2 answers

1

Every 3 bytes are converted into 4 characters, because only 7 bits of each character are used to encode information. The destination array must be at least that size.

Also keep in mind that if there is any byte anymore because the size is not a multiple of 3, 4 more bytes are needed. That is, for 5 input bytes you will need 8 output, as if they were 6.

    
answered by 03.07.2017 / 23:25
source
0

You're missing the size of the char type.

            var binaryData = File.ReadAllBytes("black-stormtrooper-64.png");

            long tamañoChar = sizeof(char);
            long arrayLength = binaryData.Length * tamañoChar;

            /*Normalizo en caso de que no termine de completar el tamaño.*/
            if (arrayLength % tamañoChar != 0)
            {
                arrayLength += tamañoChar - arrayLength % tamañoChar;
            }

            char[] base64CharArray = new char[arrayLength];

            Convert.ToBase64CharArray(binaryData, 0, binaryData.Length, base64CharArray, 0);
            var res = Encoding.ASCII.GetBytes(base64CharArray);

As an alternative to your code, you can do:

var binaryData = File.ReadAllBytes("black-stormtrooper-64.png");
string base64String = Convert.ToBase64String(binaryData);
    
answered by 03.07.2017 в 16:24