小编chi*_*g p的帖子

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

我想验证输入字符串是否有效 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)

.net c# asp.net asp.net-mvc asp.net-mvc-4

1
推荐指数
1
解决办法
8007
查看次数

标签 统计

.net ×1

asp.net ×1

asp.net-mvc ×1

asp.net-mvc-4 ×1

c# ×1