验证字符串是否为正确的 Base64String 并转换为 byte[]

chi*_*g p 1 .net c# asp.net asp.net-mvc asp.net-mvc-4

我想验证输入字符串是否有效 Base64。如果有效则转换为 byte[]。

我尝试了以下解决方案

  1. RegEx
  2. MemoryStream
  3. Convert.FromBase64String

例如,我想验证是否"932rnqia38y2"是有效的 Base64 字符串,然后将其转换为byte[]. 该字符串不是有效的 Base64,但我在代码中总是得到 true 或 valid。

如果您有任何解决方案,请告诉我。

代码

//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;
    }
}
Run Code Online (Sandbox Code Playgroud)

Uri*_*iil 6

只需创建一些帮助程序,它将捕获输入字符串上的 FormatException:

    public static bool TryGetFromBase64String(string input, out byte[] output)
    {
        output = null;
        try
        {
            output = Convert.FromBase64String(input);
            return true;
        }
        catch (FormatException)
        {
            return false;
        }
    }
Run Code Online (Sandbox Code Playgroud)