0

i have to convert base64 string to file and it could be any thing like pdf,jpg,png,txt etc without saving on disk.

I have to apply server side file size validation in webapi post method and my post method received base64 encoded string that represent any format file,now i have to identity the file size from this base64 string without saving on disk.

could you help me how can i implement this.

3
  • A file is just a bytepattern written onto the disk. Keeping that pattern in memory is not that hard. Just do not write it down before you are finished. In practice you often need streams. And there is the class "MemoryStream" wich is a stream, but keeps all the data in memory. Commented Jun 14, 2018 at 22:31
  • Console.WriteLine($"{Convert.FromBase64String("VGVzdGluZw==").Length}"); is a simple solution. Commented Jun 14, 2018 at 22:33
  • can you provide some code sample for the same. Commented Jun 14, 2018 at 22:35

1 Answer 1

1

While Convert.FromBase64String(base64).Length approach works, if you just want to find the length of the decoded Base64 bytes you could easily calculate it with out actually needing to decode your input and therefore save memory.

In general 4 Base64 characters are converted to 3 bytes. If the amount of bytes is not divisible by 3 '=' characters are used as padding to get to a full 4 character block. Also whitespace is ignored, during decoding.

int DecodedLength(string base64)
{
    var chars = 0;
    var padding = 0;
    for (int i = 0; i < base64.Length; i++)
    {
        var ch = base64[i];
        if (!char.IsWhiteSpace(ch)) { chars++; }
        if (ch == '=') { padding++; }
    }
    return chars / 4 * 3 - padding;
}

Or if you want a LINQ oneliner, which is however slightly less performant as it's iterating twice over the input and relying on enumerator calls:

int DecodedLength(string base64)
{ return (base64.Count(ch => !char.IsWhiteSpace(ch)) / 4 * 3 - base64.Count(ch => ch == '=')); }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.