How do you convert a string to a byte array in .NET?

.NetStringBytearray

.Net Problem Overview


I have a string that I need to convert to the equivalent array of bytes in .NET.

This ought to be easy, but I am having a brain cramp.

.Net Solutions


Solution 1 - .Net

You need to use an encoding (System.Text.Encoding) to tell .NET what you expect as the output. For example, in UTF-16 (= System.Text.Encoding.Unicode):

var result = System.Text.Encoding.Unicode.GetBytes(text);

Solution 2 - .Net

First work out which encoding you want: you need to know a bit about Unicode first.

Next work out which System.Text.Encoding that corresponds to. My Core .NET refcard describes most of the common ones, and how to get an instance (e.g. by a static property of Encoding or by calling a Encoding.GetEncoding.

Finally, work out whether you want all the bytes at once (which is the easiest way of working - call Encoding.GetBytes(string) once and you're done) or whether you need to break it into chunks - in which case you'll want to use Encoding.GetEncoder and then encode a bit at a time. The encoder takes care of keeping the state between calls, in case you need to break off half way through a character, for example.

Solution 3 - .Net

What Encoding are you using? Konrad's got it pretty much down, but there are others out there and you could get goofy results with the wrong one:

byte[] bytes = System.Text.Encoding.XXX.GetBytes(text)

Where XXX can be:

ASCII
BigEndianUnicode
Default
Unicode
UTF32
UTF7
UTF8

Solution 4 - .Net

Like this:

    string test = "text";
    byte[] arr = Encoding.UTF8.GetBytes(test);

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJonStonecashView Question on Stackoverflow
Solution 1 - .NetKonrad RudolphView Answer on Stackoverflow
Solution 2 - .NetJon SkeetView Answer on Stackoverflow
Solution 3 - .NetswilliamsView Answer on Stackoverflow
Solution 4 - .NetIgal TabachnikView Answer on Stackoverflow