2012-01-06 29 views
0

我有如下的方法:如何确保一个字节数组由Base64编码?

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方法应抛出异常。

如何实现这一目标?

谢谢,

+0

这个问题很不清楚。为什么使用'DecodeFrom64'如果你想编码一些东西?请详细说明你正在努力达到的目标。 – Oded 2012-01-06 10:32:14

+0

如果您阅读它,问题中的标题非常清晰。如何确保AddAttachment方法接受用Base64编码的字节数组?我也更新了身体。 – 2012-01-06 10:35:13

+0

重复这个问题并没有使它更清晰。你想在这里做什么?究竟? – Oded 2012-01-06 10:36:25

回答

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) 
    ... 
} 
+0

谢谢,但“字符串attchment”是不相关的。我需要在AddAttachment方法中进行验证,以确保它接收到正确编码的字节数组。清楚吗? – 2012-01-06 10:47:00

+0

你的意思是byte []实际上是一个base64字符串吗? – Bas 2012-01-06 10:48:04

+0

例如,在发送到此方法之前,这是有效的编码字节:byte [] attachmentInBytes = System.Convert.FromBase64String(attachmentInString); – 2012-01-06 10:51:55

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 
    } 
} 
相关问题