valch valch - 11 months ago 79
C# Question

How to convert utf8 string to utf8 byte array?

How can I convert string to utf8 byte array, I have this sample code:

This works ok:

StreamWriter file = new StreamWriter(file1, false, Encoding.UTF8);

This works wrong, file is in ASCII:

byte[] bytes = System.Text.UTF8Encoding.UTF8.GetBytes(utf8string);
FileStream fs = new FileStream(file2, FileMode.CreateNew);
fs.Write(bytes, 0, bytes.Length);

I would like to get byte array what returned by this function:


because this works ok:

byte[] datab = File.ReadAllBytes(file1);
FileStream fs2 = new FileStream(file3, FileMode.CreateNew);
fs2.Write(datab, 0, datab.Length);

Answer Source

Can use other option again:

string value = "\u00C4 \uD802\u0033 \u00AE";    
byte[] bytes= System.Text.Encoding.UTF8.GetBytes(value);

For more information can look on Encoding.UTF8 Property