【问题标题】:how to make sure that an array of bytes is encoded by Base64?如何确保一个字节数组是由 Base64 编码的?
【发布时间】:2012-02-04 02:22:45
【问题描述】:

我有一个方法如下:

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

如何做到这一点?

谢谢,

【问题讨论】:

  • 这个问题很不清楚。如果你想encode 东西,为什么要使用DecodeFrom64?请准确说明您要达到的目标。
  • 问题中的标题读了就很清楚了。如何确保 AddAttachment 方法接受使用 Base64 编码的字节数组?我也更新了正文。
  • 重复这个问题并不能使它更清楚。你想在这里达到什么目的?对吗?
  • @Oded 他想检查附件是否用base64编码。
  • 你的例子完全没有意义。 FromBase64String 的输出可以是任何可能的byte[],因为这是解码操作,而不是编码操作。此外,由于"Hello test" 不是有效的base64 字符串,它无论如何都会失败。

标签: c# encoding bytearray base64 decoding


【解决方案1】:

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

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

如果要将附件编码为base64:

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

【讨论】:

  • 谢谢,但“字符串附件”不相关。我需要在 AddAttachment 方法中进行验证,以确保它接收到正确编码的字节数组。清楚了吗?
  • 你的意思是字节[]实际上是一个base64字符串?
  • 例如,这是发送到此方法之前的有效编码字节:byte[] attachmentInBytes = System.Convert.FromBase64String(attachmentInString);
【解决方案2】:

从你的问题我发现你误解了一些东西,希望这会有所帮助。 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
   }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-23
    • 1970-01-01
    • 2020-10-26
    • 2011-11-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多