Obi
Obi

Reputation: 3091

Validate Base64 string

I am converting an image to base64 on a html5 mobile client and posting the string to my webapi service. I try to convert the received string back to an image and I get the following exception

The input is not a valid Base-64 string as it contains a non-base 64 character, more than two padding characters, or an illegal character among the padding characters.

Pastebin of base64 string is here.

I have read all the suggestions about replaing wrong characters so I wroe this function to and pass my strings into it first yet no luck.

    private string FixBase64ForImage(string Image)
    {
        System.Text.StringBuilder sbText = new System.Text.StringBuilder(Image, Image.Length);

        sbText.Replace("\r\n", String.Empty);

        sbText.Replace(" ", String.Empty);

        sbText.Replace('-', '+');

        sbText.Replace('_', '/');

        sbText.Replace(@"\/", "/");

        return sbText.ToString();
    }

Is there a way to know exactly what character is causing the conversion to fail?

Upvotes: 0

Views: 2325

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1500505

My guess is that you're including the "data:image/png;base64," part at the start of the string - you need to strip that first. You don't need to do anything else - with the text in the pastebin, Convert.FromBase64String handles everything after the "base64," with no problems at all.

Upvotes: 4

Related Questions