8

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.

Community
  • 1
  • 1
Edward83
  • 6,664
  • 14
  • 74
  • 102
  • 3
    That question has a rather misleading accepted answer, depending on the behavior of the runtime serialization output, which is certainly not cross-language-compatible. Therefore I am not going to vote to close as a duplicate. Using a proper encoding, like UTF-8, is a much better approach. – cdhowie Nov 30 '10 at 21:15
  • 2
    @cdhowie: agreed. "Rather misleading" is a polite way to put it. :) – MusiGenesis Nov 30 '10 at 21:20
  • Presumably that's why there is a better answer with higher votes just underneath. – Steve Townsend Nov 30 '10 at 21:29

4 Answers4

21

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);
cdhowie
  • 158,093
  • 24
  • 286
  • 300
8

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.

Will Vousden
  • 32,488
  • 9
  • 84
  • 95
3

Use the Encoding class.

Oded
  • 489,969
  • 99
  • 883
  • 1,009