8

How do you get a byte array out of a string in C#? I would like to pass a string to this method.

Louis Rhys
  • 30,777
  • 53
  • 137
  • 211
  • This is an exact duplicate.. http://stackoverflow.com/questions/472906/net-string-to-byte-array-c – Jaco Pretorius Sep 27 '10 at 09:40
  • Also a duplicate of this... http://stackoverflow.com/questions/241405/how-do-you-convert-a-string-to-a-byte-array-in-net – Jaco Pretorius Sep 27 '10 at 09:41
  • 1
    @Jaco Pretorius: Yes, I guess so, but I don't like the accepted answers in either of those. I like the accepted answer in this one. Always use UTF-8 unless you have a very good reason to use something else. – President James K. Polk Sep 27 '10 at 22:25

4 Answers4

7
Encoding.UTF8.GetBytes("abcd");
Noffls
  • 5,159
  • 2
  • 27
  • 35
  • 1
    Can you explain why you used UTF8? – Louis Rhys Aug 01 '11 at 04:30
  • 1
    It's just an example. But UTF8 is very common. `Encoding.Default` would be another good example. See [Encoding Properties](http://msdn.microsoft.com/de-de/library/system.text.encoding_properties.aspx) for more Information – Noffls Aug 01 '11 at 05:46
2

Try

public static byte[] StrToByteArray(string str)
{
    System.Text.UTF8Encoding  encoding=new System.Text.UTF8Encoding();
    return encoding.GetBytes(str);
}
Thariama
  • 47,807
  • 11
  • 127
  • 149
1

Use GetBytes( )

Sachin Shanbhag
  • 50,935
  • 9
  • 84
  • 103
0

Encoding.GetBytes method.

Itay Karo
  • 16,882
  • 3
  • 36
  • 56