C# 将字符串验证为正确的Base64String并转换为字节[]
我想验证输入字符串是否为有效的Base64。如果有效,则转换为字节[] 我尝试了以下解决方案C# 将字符串验证为正确的Base64String并转换为字节[],c#,asp.net,.net,asp.net-mvc,asp.net-mvc-4,C#,Asp.net,.net,Asp.net Mvc,Asp.net Mvc 4,我想验证输入字符串是否为有效的Base64。如果有效,则转换为字节[] 我尝试了以下解决方案 RegEx MemoryStream Convert.FromBase64String 例如,我想验证“932rnqia38y2”是否为有效的Base64字符串,然后将其转换为字节[]。此字符串在Base64中无效,但我在代码中总是得到true或valid 如果您有任何解决方案,请告诉我 代码 //Regex _rx = new Regex(@"^(?:[A-Za-z0-9+/]{4})*(?:[A-Z
RegEx
MemoryStream
Convert.FromBase64String
“932rnqia38y2”
是否为有效的Base64字符串,然后将其转换为字节[]
。此字符串在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;
}
}
只需创建一些助手,它将捕获输入字符串上的FormatException:
public static bool TryGetFromBase64String(string input, out byte[] output)
{
output = null;
try
{
output = Convert.FromBase64String(input);
return true;
}
catch (FormatException)
{
return false;
}
}
932RN38Y2在我看来是有效的。只需调用base64string并捕获潜在异常就足够了。我认为您无法检查是否可以使用正则表达式将字符串解释为Base-64。在任何情况下,您试图验证的字符串都是有效的,因此您得到正确的结果也就不足为奇了。字符串中的数据是否有效是一个完全不同的问题。