【问题标题】:The input is not a valid Base-64 string输入不是有效的 Base-64 字符串
【发布时间】:2019-10-10 12:23:24
【问题描述】:

FromBase64String 方法面临的问题。

输入不是有效的 Base-64 字符串,因为它包含非 base 64 字符、两个以上的填充字符或填充字符中的非法字符。

尝试将- 替换为+

var bytes = Convert.FromBase64String(id);
id = "59216167-f9c0-4b1b-b1db-1babd1209f10@ABC"

预期结果是字符串应转换为等效的 8 位无符号整数数组。

【问题讨论】:

  • 尝试将 '-' 字符转换为 '+' 字符仍然无法正常工作
  • 欢迎来到 StackOverflow。是的,这是一个无效的 base64 字符串。您希望我们做什么?

标签: c# base64


【解决方案1】:

它不是 Base64 编码的字符串。这是一个向导。您可以像这样将其读入字节数组

var bytearray = new Guid("59216167-f9c0-4b1b-b1db-1babd1209f10").ToByteArray();

【讨论】:

  • TBH,它甚至不是一个有效的Guid。运行时错误应该是Guid should contain 32 digits with 4 dashes。具体在 OP 原帖中,那个 Guid 的实际问题是最后 4 个字符; @ABC,删除它们会成功。因此,我建议更新您的帖子以包含它甚至不是有效的 Guid...
【解决方案2】:

输入不是有效的 Base-64 字符串

您收到此类错误的确切原因是 它不是有效的 Base64 字符串,而是如前所述,它是 Guid;并且不是有效的指导

首先,您可以通过尝试转换来检查您是否有一个有效的Base64 字符串。

public static bool StringIsBase64(string myString)
{
   Span<byte> buffer = new Span<byte>(new byte[myString.Length]);
   return Convert.TryFromBase64String(myString, buffer , out int bytesParsed);
}

现在如果你调用这个函数并且它成功了,那么我们会假设你确实有一个有效的Base64 字符串,否则会发生转换错误。

您的通话现在看起来像这样:

 string id = "59216167-f9c0-4b1b-b1db-1babd1209f10@ABC";
 var bytes;
 if (StringIsBase64(id))
 {
    bytes = Convert.FromBase64String(id);
 } 

我想解决的其他问题是,输入 即使是 Guid 也无效GUID 是一个 128 位整数(16 个字节),该字符串无效。

你实际上会收到错误:

Guid 应包含 32 位数字和 4 个破折号 (xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx)

字符串末尾的字符@ABC 会导致这种情况,如果将这些字符删除,那么我们就有一个实际有效的Guid

【讨论】:

    【解决方案3】:

    试试这个会有帮助

        using System;
        public class Program{
    
        public static void Main()
        {
            Guid gg = Guid.NewGuid();
            Console.WriteLine(gg);
            string ss = Encode(gg);
            Console.WriteLine(ss);
            Console.WriteLine(Decode(ss));
        }
        public static string Encode(Guid guid)
        {
            string encoded = Convert.ToBase64String(guid.ToByteArray());
            encoded = encoded.Replace("/", "_").Replace("+", "-");
            return encoded.Substring(0, 22);
        }
    
        public static Guid Decode(string value)
        {
            value = value.Replace("_", "/").Replace("-", "+");
            byte[] buffer = Convert.FromBase64String(value + "==");
            return new Guid(buffer);
        }
    
    
    
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多