使用 C# 将二进制数据字符串存储到字节数组中
我有一个以字符串形式返回二进制数据的网络服务。使用 C# 代码如何将其存储在字节数组中?这是正确的方法吗?
System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
byte[] bytes = encoding.GetBytes(inputString);
事实上,这并没有起作用。让我进一步解释一下: Web 服务代码使用 utf8 编码将字符串(包含 XSLFO 数据)转换为字节数组。在我的网络服务响应中,我只看到类似的数据<代码>“PGZvOnJvb3QgeG1sbnM6Zm89Imh0dHA6Ly93d3cudzMub3JnLzE5OTkvWFNML0Zvcm1hdCIgeG 1sbnM6eGY9Imh0dHA6Ly93d3cuZWNyaW9uLmNvbS94Zi8xLjAiIHhtbG5zOm1zeHNsPSJ1c==”。实际上我希望在服务中将原始字符串值转换为 byte[] 。不确定是否可能?
I have a webservice that returns a binary data as a string. Using C# code how can I store it in byte array? Is this the right way?
System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
byte[] bytes = encoding.GetBytes(inputString);
Actually, this didn't work. Let me explain it more:
the web service code converts a string (containing XSLFO data) into byte array using utf8 encoding. In my web service response I only see data something like "PGZvOnJvb3QgeG1sbnM6Zm89Imh0dHA6Ly93d3cudzMub3JnLzE5OTkvWFNML0Zvcm1hdCIgeG1sbnM6eGY9Imh0dHA6Ly93d3cuZWNyaW9uLmNvbS94Zi8xLjAiIHhtbG5zOm1zeHNsPSJ1c=="
. Actually I would like to have the original string value that was converted into byte[] in the service. Not sure if it possible?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不,那是个坏主意。
除非输入数据最初是文本,否则尝试使用
Encoding
是一个坏主意。 Web服务应该使用类似base64的东西对其进行编码 - 此时您可以使用Convert.FromBase64String
获取原始二进制数据。基本上,将任意二进制数据视为编码文本是丢失数据的快速方法。当您需要在字符串中表示二进制数据时,您应该使用 base64、十六进制或类似的东西。
当然,这可能意味着您还需要更改 Web 服务 - 如果它通过简单地将二进制数据视为 UTF-8 编码文本来创建字符串,那么它一开始就损坏了。
No, that's a bad idea.
Unless the input data was originally text, trying to use
Encoding
is a bad idea. The web service should be using something like base64 to encode it - at which point you can useConvert.FromBase64String
to get the original binary data back.Basically, treating arbitrary binary data as if it were encoded text is a quick way to lose data. When you need to represent binary data in a string, you should use base64, hex or something similar.
This may mean you need to change the web service as well, of course - if it's creating the string by simply treating the binary data as UTF-8-encoded text, it's broken to start with.
如果字符串以 UTF8 编码进行编码,那么是的,这是正确的方法。如果是 Unicode,则非常相似:
Base64Encoding 略有不同:
If the string is encoded in UTF8 Encoding, then yes that is the correct way. If it is in Unicode it is very similar:
Base64Encoding is a little different: