37

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);
file.WriteLine(utf8string);
file.Close();

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);
fs.Close();

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

System.IO.File.ReadAllBytes(path_to_file)

because this works ok:

byte[] datab = File.ReadAllBytes(file1);
FileStream fs2 = new FileStream(file3, FileMode.CreateNew);
fs2.Write(datab, 0, datab.Length);
fs2.Close();
3
  • Why do you think your second example doesn't work? Commented Jul 18, 2012 at 10:49
  • Very similar question just asked: stackoverflow.com/questions/11539559/… Commented Jul 18, 2012 at 10:51
  • 1
    Does this not answer your question byte[] bytes = System.Text.UTF8Encoding.UTF8.GetBytes(utf8string);? Commented Jul 18, 2012 at 15:34

1 Answer 1

91

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

Sign up to request clarification or add additional context in comments.

2 Comments

Does the resulting byte array contain a trailing NULL character?
Only if the input array has one. It's a one-for-one copy.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.