gpt4 book ai didi

c# - Base64 字符串抛出无效字符错误

转载 作者:可可西里 更新时间:2023-11-01 07:55:17 25 4
gpt4 key购买 nike

我一直收到 Base64 无效字符错误,尽管我不应该这样做。

该程序获取一个 XML 文件并将其导出到一个文档中。如果用户需要,它也会压缩文件。压缩工作正常并返回一个 Base64 字符串,该字符串被编码为 UTF-8 并写入文件。

当需要将文档重新加载到程序中时,我必须检查它是否已压缩,代码很简单:

byte[] gzBuffer = System.Convert.FromBase64String(text);
return "1F-8B-08" == BitConverter.ToString(new List<Byte>(gzBuffer).GetRange(4, 3).ToArray());

它检查字符串的开头以查看其中是否包含 GZip 代码。

现在的问题是,我的所有测试都有效。我获取一个字符串,对其进行压缩、解压缩,并将其与原始字符串进行比较。问题是当我得到从 ADO 记录集返回的字符串时。该字符串正是写入文件的内容(在末尾添加了一个“\0”,但我认为它甚至没有做任何事情,即使被删除它仍然会抛出)。我什至将整个字符串复制并粘贴到测试方法中并压缩/解压缩。工作正常。

测试会通过,但代码会使用完全相同的字符串失败?唯一的区别是,我不是仅仅声明一个常规字符串并将其传递进去,而是从记录集中返回一个字符串。

关于我做错了什么有什么想法吗?

最佳答案

你说

The string is exactly what was written to the file (with the addition of a "\0" at the end, but I don't think that even does anything).

事实上,它确实做了一些事情(它会导致您的代码抛出 FormatException:"Invalid character in a Base-64 string"),因为 Convert.FromBase64String不认为“\0”是有效的 Base64 字符。

  byte[] data1 = Convert.FromBase64String("AAAA\0"); // Throws exception
byte[] data2 = Convert.FromBase64String("AAAA"); // Works

解决方案:摆脱零终止。(也许调用 .Trim("\0"))

注意事项:

MSDN docs for Convert.FromBase64String说它会抛出 FormatException when

The length of s, ignoring white space characters, is not zero or a multiple of 4.

-or-

The format of s is invalid. s contains a non-base 64 character, more than two padding characters, or a non-white space character among the padding characters.

还有那个

The base 64 digits in ascending order from zero are the uppercase characters 'A' to 'Z', lowercase characters 'a' to 'z', numerals '0' to '9', and the symbols '+' and '/'.

关于c# - Base64 字符串抛出无效字符错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/710853/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com