Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PadRight() isn't padding at all

Tags:

string

c#

asp.net

I'm trying to use the String.PadRight method in C#, but it's just not doing anything with the string.

Code:

int strlen = 4 - (data.Length % 4);
char pad = '=';
string datapad = data.PadRight(strlen, pad);

The string in question is Base64 encoded data, and I need the '=' at the end to pad it for ConvertFromBase64 to work properly.

eyJhbGciOiJSUzI1NiIsImtpZCI6IjY5NDZmZjNlZGUyOTk3ZWExMmVhMDRlNGFhNjYyOWRjZWVhZWZhOTAifQ
like image 843
ClairelyClaire Avatar asked Sep 19 '25 06:09

ClairelyClaire


1 Answers

strlen must be greater than the length of data in order for it to pad it. As Grant Winney points out, PadRight takes the total width of the string, and not just the number of times you'd like to repeat that character at the end of it.

In the code below, strlen will always be less than or equal to 4, which is a lot less than the length of your base 64 encoded string.

int strlen = 4 - (data.Length % 4);

So really you might want to do this instead:

int strlen = 4 - (data.Length % 4) + data.Length;

Or just:

string datapad = data.PadRight(strlen + data.Length, pad);
like image 160
sgbj Avatar answered Sep 21 '25 23:09

sgbj