Reputation: 2439
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.
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();
Upvotes: 1
Views: 345
Reputation: 24525
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. However, .NET strings are always either UNICODE
or UTF-16
.
MemoryStream from string - confusion about Encoding to use
I would suggest using System.Convert.ToBase64String(someByteArray)
and its counterpart System.Convert.FromBase64String(someString)
to handle this for you.
Upvotes: 2
Reputation: 370
This looks like base 64. Use:
System.Convert.ToBase64String(b)
https://msdn.microsoft.com/en-us/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
Upvotes: 4
Reputation: 27357
You need to de-code it from base64
, like this:
Assuming you've read the file into ss
as a string.
var bytes = Convert.FromBase64String(ss);
Upvotes: 3