chirag patel

chirag patel

  • NA
  • 7
  • 15.9k

Validate string as Proper Base64String and Convert to byte[]

Aug 8 2016 6:43 AM
Hi all,
 
i want to validate input string is Valid Base64String or not, if its valid then convert into byte[].
 
i try following solutions
1) Use RegEx
2) Use MemoryStream
3) Use Convert.FromBase64String
 
For example i want to validate this string "932rnqia38y2" its Base64String or not and then convert to byte[], this string is not valid Base64String but i am 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;
}
}

Answers (2)