Alexander
Alexander

Reputation: 1612

Cannot split Base64 string the correct way

I'm working on a C# client that receives Base64 files via a website.

It worked sometimes, but now I have a file that doesn't work because:

Lets say I have this as a Base64 string with some extra information added at the beginning shapered.png|data:image/png;base64,iVBORw0KGgoAAAANSUh /// EUgAAACAAAAAgCAYAblabla

Then I do this in the C# code:

var raw = base64.Split('/')[1]; //get raw data with type extention ,
var data = raw.Split(',')[1]; //get base64 data
var info = raw.Split(',')[0]; // gets type extention mp3 base64 
var ext = info.Split(';')[0]; // splits header mp3 only use this for comparison against malicous file
var name = base64.Split('|')[0]; //splits name info

Now I see in the debugger that it cuts all the information out after at the ///

Am I completely missing the point? I'd think that var raw = base64.Split('/')[1] would take the information after date:image/ and then that raw.Split(',')[1] takes out the png;base64 with only the raw data being left.

But it doesn't, it also takes out all the rest after the '/' out in the raw variable resulting in making the file corrupt.

Reason why I'm not splitting it at the ',' immediatly and split from there is to prevent files with a ',' in it to also work.

It totally flew above my head, sorry guys! I thought in one way that with [1] it would also take the rest of the "array".

        string example = "im/noob/programmer";
        Console.WriteLine(example);
        string lol = example.Split('/')[1]; //this only outputs "noob"
        Console.WriteLine(lol);

Upvotes: 1

Views: 7477

Answers (1)

Patrick Hofman
Patrick Hofman

Reputation: 157098

You are cutting the entire string up in pieces. You use the / to do that splitting and it breaks the string off at every occurrence of a /.

The better solution is to find the position of the slash instead of splitting on it.

Something like this:

string s1 = "shapered.png|data:image/png;base64,iVBORw0KGgoAAAANSUh /// EUgAAACAAAAAgCAYAblabla";
string name = s1.Substring(0, s1.IndexOf('|'));
string data = s1.Substring(s1.IndexOf('|') + 1);
string mimeType = data.Substring(data.IndexOf(':') + 1, data.IndexOf(';') - data.IndexOf(':') - 1);
string base64 = data.Substring(data.IndexOf(',') + 1);

Or when you are comfortable to use a regular expression:

(.*?)\|data:(.*?);base64,(.*)

Upvotes: 2

Related Questions