Reputation: 41
I want to validate if an input string is valid Base64 or not. If it's valid then convert into byte[].
I tried the following solutions
RegEx
MemoryStream
Convert.FromBase64String
For example I want to validate if "932rnqia38y2"
is a valid Base64 string or not and then convert it to byte[]
. This string is not valid Base64 but I'm always getting true or valid in my code.
please let me know if you have any solutions.
Code
//Regex _rx = new Regex(@"^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}[AEIMQUYcgkosw048]=|[A-Za-z0-9+/][AQgw]==)?$", RegexOptions.Compiled);
Regex _rx = new Regex(@"^([A-Za-z0-9+/]{4})*([A-Za-z0-9+/]{4}|[A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{2}==)$", RegexOptions.Compiled);
if (image == null) return null;
if ((image.Length % 4 == 0) && _rx.IsMatch(image))
{
try
{
//MemoryStream stream = new MemoryStream(Convert.FromBase64String(image));
return Convert.FromBase64String(image);
}
catch (FormatException)
{
return null;
}
}
Upvotes: 2
Views: 8619
Reputation: 12618
Just create some helper, which will catch FormatException on input string:
public static bool TryGetFromBase64String(string input, out byte[] output)
{
output = null;
try
{
output = Convert.FromBase64String(input);
return true;
}
catch (FormatException)
{
return false;
}
}
Upvotes: 7