简体   繁体   中英

Create properly escaped string from byte array

I have a byte array, read from an image file, that I am trying to send from C# across a socket to a Meteor server running collectionFS (v0.3.7).

I am trying to convert it to a string to match the result I would get from calling FileReader.readAsBinaryString() in JavaScript, for example:

?PNG\r\n\u001a\n\u0000\u0000\u0000\rIHDR\u0000\u0000\u0003?\u0000\u0000\u0002?

In my C# code, I have tried using System.Text.Encoding.UTF8.GetString() , which gives me something like this:

�PNG\r\n\n\0\0\0\rIHDR\0\0�\0\0

This fails on the transfer, presumably because the '\\0' is treated like the end of the string.

Can anyone better explain what is happening here? Is there a nice way in C# to format the bytes using the unicode escape sequences like readAsBinaryString() does?

EDIT: The eventual destination for this data is a BSON binary entry in MongoDB (in Meteor), to be later extracted (as a Blob) and viewed through the normal Meteor web browser client.

There is no built in method that does exactly that.

To transform byte array to encoded you need to decide what is encoded and what is not. Looks like 0-9a-zA-Z range should not be encoded and the rest encoded as \\uXXXX :

I'd do something like following:

var result = String.Join("", byteArray
   .Select(b => b >'0' && b <'9' ? 
       (char)b.ToString() : String.Format(@"\u{0:x4}", b)));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM