[英]Validate string as Proper Base64String and Convert to byte[]
我想验证输入字符串是否有效的Base64。 如果有效,则转换为byte []。
我尝试了以下解决方案
RegEx
MemoryStream
Convert.FromBase64String
例如,我想验证"932rnqia38y2"
是否为有效的Base64字符串,然后将其转换为byte[]
。 这个字符串不是有效的Base64,但是我的代码中总是正确或有效的。
如果您有任何解决方案,请告诉我。
码
//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;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.