How do you get a byte array out of a string in C#? I would like to pass a string to this method.
Asked
Active
Viewed 2,253 times
8
-
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 Answers
8
Encoding.UTF8.GetBytes("abcd");

Noffls
- 5,397
- 2
- 29
- 36
-
1
-
1It'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
- 50,002
- 13
- 138
- 166
-
4Why create a new instance of UTF8Encoding when you can use Encoding.UTF8? – Jon Skeet Sep 27 '10 at 09:39
-