My input string consists of a mixture of unicode escape characters with regular characters mixed in. Example:
\u0000\u0003\u0000\u0013timestamp\u0011clientId\u0015timeToLive\u0017destination\u000fheaders\tbody\u0013messageId\u0001\u0006
How can I convert this into a bytearray or Stream?
EDIT: UTF+8 encoding. To clarify the input string:
Char 01: U+0000 Char 02: U+0003 Char 03: U+0000 Char 04: U+0013 Char 05: t Char 06: i Char 07: m Char 08: e Char 09: s Char 10: t Char 11: a Char 12: m Char 13: p Char 14: U+0011 ... ...
Okay, so you've got an arbitrary string (the fact that it contains non-printable characters is irrelevant) and you want to convert it into a byte array using UTF-8. That's easy :)
byte[] bytes = Encoding.UTF8.GetBytes(text);
Or to write to a stream, you'd normally wrap it in a StreamWriter
:
// Note that due to the using statement, this will close the stream at the end // of the block using (var writer = new StreamWriter(stream)) { writer.Write(text); }
(UTF-8 is the default encoding for StreamWriter
, but you can specify it explicitly of course.)
I'm assuming you really have a good reason to have "text" in this form though. I can't say I've ever found a use for U+0003 (END OF TEXT). If, as I4V has suggested, this data was originally in a binary stream, you should avoid handling it as text in the first place. Separate out your binary data from your text data - when you mix them, it will cause issues. (For example, if the fourth character in your string were U+00FF, it would end up as two bytes when encoded to UTF-8, which probably wouldn't be what you wanted.)
To simplify the conversion just do this:
var stream = new memoryStream(Encoding.UTF8.GetBytes(str));
Or if you want a approach that have concerns about reusability, create a Extension Method to strings like this:
public static class StringExtension { public static Stream ToStream(this string str) =>new memoryStream(Encoding.UTF8.GetBytes(str)) //Or much better public static Stream ToStreamWithEncoding(this string str, Encoding encoding) =>new memoryStream(encoding.GetBytes(str)) }