Hi IamAzhar,
Use below method to check valid base64 string.
C#
public bool IsBase64String(string base64)
{
base64 = base64.Trim();
return (base64.Length % 4 == 0) && Regex.IsMatch(base64, @"^[a-zA-Z0-9\+/]*={0,3}$", RegexOptions.None);
}
VB.Net
Public Function IsBase64String(ByVal base64 As String) As Boolean
base64 = base64.Trim()
Return (base64.Length Mod 4 = 0) AndAlso Regex.IsMatch(base64, "^[a-zA-Z0-9\+/]*={0,3}$", RegexOptions.None)
End Function
Or you can use try catch.
C#
public static bool TryGetFromBase64String(string input, out byte[] output)
{
output = null;
try
{
output = Convert.FromBase64String(input);
return true;
}
catch (FormatException ex)
{
return false;
}
}
VB.Net
Public Shared Function TryGetFromBase64String(ByVal input As String, <Out> ByRef output As Byte()) As Boolean
output = Nothing
Try
output = Convert.FromBase64String(input)
Return True
Catch ex As FormatException
Return False
End Try
End Function
Or refer below link.
https://stackoverflow.com/questions/6309379/how-to-check-for-a-valid-base64-encoded-string