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();
5
  • How is the string encoded? I've had issues similar to this, and I had to decode the string to get the correct byte[] Commented Nov 17, 2015 at 12:48
  • 1
    I don't think I added any encoding for the file. Its simple returned from binary column of DB Commented Nov 17, 2015 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. Commented Nov 17, 2015 at 12:50
  • As an aside OP, make sure you're disposing your objects where necessary. msdn.microsoft.com/en-us/library/yh598w02.aspx Commented Nov 17, 2015 at 12:52
  • @LucasTrzesniewski - no you don't. If it looks like Base64 then you can use FromBase64String() as the other answers suggest. Commented Nov 17, 2015 at 12:53

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

Comments

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);

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.