1

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();
Moiz
  • 2,409
  • 5
  • 27
  • 50
  • How is the string encoded? I've had issues similar to this, and I had to decode the string to get the correct byte[] – Vlad274 Nov 17 '15 at 12:48
  • 1
    I don't think I added any encoding for the file. Its simple returned from binary column of DB – Moiz Nov 17 '15 at 12:50
  • 1
    Your string seems to be a base64-encoded ZIP file. You need to know in exactly what format it is before you can do anything. – Lucas Trzesniewski Nov 17 '15 at 12:50
  • As an aside OP, make sure you're disposing your objects where necessary. https://msdn.microsoft.com/en-us/library/yh598w02.aspx –  Nov 17 '15 at 12:52
  • @LucasTrzesniewski - no you don't. If it looks like Base64 then you can use `FromBase64String()` as the other answers suggest. –  Nov 17 '15 at 12:53

3 Answers3

4

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

User42
  • 370
  • 1
  • 5
3

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);
Rob
  • 26,989
  • 16
  • 82
  • 98
2

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.

Community
  • 1
  • 1
David Pine
  • 23,787
  • 10
  • 79
  • 107