如何确保Base64编码一个字节数组?

时间:2012-01-06 10:29:39

标签: c# encoding bytearray base64 decoding

我有一个方法如下:

public void AddAttachment(byte[] attachment)
{
// how to make sure that the attachemnt is encoded by Base64?
}

如何确保AddAttachment方法接受用Base64编码的字节数组?

例如,以下是发送到此方法之前的有效输入:

string attachmentInString = "Hello test";
byte[] attachmentInBytes = System.Convert.FromBase64String(attachmentInString);

但如果attachmentInBytes是使用ASCII或等编码的,则AddAttachement方法应抛出异常。

如何实现这一目标?

谢谢,

2 个答案:

答案 0 :(得分:0)

Base64是一种将字节流表示为字符串的方法。如果您希望附件为base64字符串,请将签名更改为public void AddAttachment(string attachment)

然后使用byte[] data = Convert.FromBase64String(attachment)

解码Base64

如果要将附件编码为base64:

public void AddAttachment(byte[] attachment) {
   string base64 = Convert.ToBase64String(attachment)
   ...
}

答案 1 :(得分:0)

从你的问题我发现你误解了一些东西,希望这会有所帮助。 Convert.FromBase64String接受一个字符串(总是像ALJWKA==)并输出byte[],而Convert.ToBase64String则相反。所以你的代码:

string attachmentInString = "Hello test";
byte[] attachmentInBytes = System.Convert.FromBase64String(attachmentInString);

将抛出异常,因为“Hello test”不是有效的base64字符串。参见其他方法

public void AddAttachment(byte[] attachment)

参数是byte[],因此在此方法中,您最多将其转换为类似字符串的base64。您无法判断byte[]是否是有效的base64字符串。您只能对字符串执行此操作:

public void AddAttachment(string attachment) //well I know it looks strange
{
   byte[] bytes = null;
   try
   {
       bytes = Convert.FromBase64String(attachment);
   }
   catch
   {
       //invalid string format
   }
}