Reputation:
I have a array byte[]. It contains the lines of a string[], seperated with line breaks. What would the best way to get the string[] back from the byte[]? Encoding is utf-8.
byte[] lines[];
string[] str = Encoding.UTF8.GetString(lines).Split(new string[] { "\r\n", "\n" }, StringSplitOptions.None);
Would be an option, but maybe there is a better way.
Upvotes: 2
Views: 131
Reputation: 6434
Dependent on your source of string[]
, you could potentially use BinaryFormatter
and then Serialize
your string[]
to a byte[]
first off and then Deserialize
back to a string[]
later on; however this means that you will need the string[]
first off so it sort of defeats the object...
The code you have mentioned is probably the best way, if I am perfectly honest and as other have suggested - you can read each byte with a StringBuilder
but that is probably even messier.
Here is the link to BinaryFormatter
Upvotes: 0
Reputation: 4733
I think that solution you provided in quiestion is the best way. I don't know any other methods of getting string from byte array (knowing the encoding) or splitting string into array.
Upvotes: 1