[英]Converting a byte[] string back to byte[] array
I have one scenario with class like this. 我有一个这样的类场景。
Class Document
{
public string Name {get;set;}
public byte[] Contents {get;set;}
}
Now I am trying to implement the import export functionality where I keep the document in binary so the document will be in json file with other fields and the document will be something in this format. 现在,我正在尝试实现导入导出功能,在该功能中,我将文档保留为二进制格式,因此该文档将与其他字段一起位于json文件中,并且该文档将采用这种格式。
UEsDBBQABgAIAAAAIQCitGbRsgEAALEHAAATAAgCW0NvbnRlbnRfVHlwZXNdLnhtbCCiBAIooAACAAAAAAA==
Now when I upload this file back, I get this file as a string and I get the same data but when I try to convert this in binary bytes[] the file become corrupt. 现在,当我将该文件上传回时,我将该文件作为字符串获得,并且得到相同的数据,但是当我尝试将其转换为二进制字节[]时,该文件已损坏。
How can I achieve this ? 我该如何实现?
I use something like this to convert 我用这样的东西来转换
var ss = sr.ReadToEnd();
MemoryStream stream = new MemoryStream();
StreamWriter writer = new StreamWriter(stream);
writer.Write(ss);
writer.Flush();
stream.Position = 0;
var bytes = default(byte[]);
bytes = stream.ToArray();
This looks like base 64. Use: 看起来像以64为底。使用:
System.Convert.ToBase64String(b)
https://msdn.microsoft.com/en-us/library/dhx0d524%28v=vs.110%29.aspx https://msdn.microsoft.com/zh-CN/library/dhx0d524%28v=vs.110%29.aspx
And 和
System.Convert.FromBase64String(s)
https://msdn.microsoft.com/en-us/library/system.convert.frombase64string%28v=vs.110%29.aspx https://msdn.microsoft.com/zh-cn/library/system.convert.frombase64string%28v=vs.110%29.aspx
You need to de-code it from base64
, like this: 您需要从base64
对其进行解码,如下所示:
Assuming you've read the file into ss
as a string. 假设您已将文件作为字符串读取到ss
中。
var bytes = Convert.FromBase64String(ss);
There are several things going on here. 这里发生了几件事。 You need to know the encoding for the default StreamWriter
, if it is not specified it defaults to UTF-8
encoding. 您需要知道默认StreamWriter
的编码,如果未指定,则默认为UTF-8
编码。 However, .NET strings are always either UNICODE
or UTF-16
. 但是,.NET字符串始终是UNICODE
或UTF-16
。
MemoryStream from string - confusion about Encoding to use 来自字符串的MemoryStream-关于使用编码的困惑
I would suggest using System.Convert.ToBase64String(someByteArray)
and its counterpart System.Convert.FromBase64String(someString)
to handle this for you. 我建议使用System.Convert.ToBase64String(someByteArray)
及其对应的System.Convert.FromBase64String(someString)
为您处理此问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.