c# - Validate string as Proper Base64String and Convert to byte[] -


i want validate if input string valid base64 or not. if it's valid convert byte[].

i tried following solutions

  1. regex
  2. memorystream
  3. convert.frombase64string

for example want validate if "932rnqia38y2" valid base64 string or not , convert byte[]. string not valid base64 i'm getting true or valid in code.

please let me know if have 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;     } } 

just create helper, 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;         }     } 

Comments

Popular posts from this blog

Spring Boot + JPA + Hibernate: Unable to locate persister -

go - Golang: panic: runtime error: invalid memory address or nil pointer dereference using bufio.Scanner -

c - double free or corruption (fasttop) -