String to byte[] and vice versa? [duplicate]
Possible Duplicate:
.NET String to byte Array C#
How do I convert String to byte[] array and vice versa? I need strings to be stored in some binary storage. Please show example in both directions. And one more thing: each string maybe bigger than 90Kb.
If you want to use UTF-8 encoding:
// string to byte[]
byte[] bytes = Encoding.UTF8.GetBytes(someString);
// byte[] to string
string anotherString = Encoding.UTF8.GetString(bytes);
Before you march off and use one of the examples someone's already given you should be aware that there is, in general, no unique mapping between a string and a sequence of bytes. How the string is mapped to binary (and vice versa) is determined by the encoding that you use. Joel Spolsky wrote an awesome article on this subject.
When decoding binary to get a string, you need to use the same encoding as was used to produce the binary in the first place, otherwise you'll run into problems.
Use the Encoding
class.
How do I get a consistent byte representation of strings in C# without manually specifying an encoding?
精彩评论