How to convert utf8 string to utf8 byte array?

﹥>﹥吖頭↗ 提交于 2020-05-25 05:48:06

问题


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();

回答1:


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




回答2:


You just wanted to convert utf8string to bytes, what are these filestreams for?

String ValueToConvert = "Stack overflow";
byte[] ConvertedBytes = ValueToConvert.getBytes("UTF-8");


来源:https://stackoverflow.com/questions/11539631/how-to-convert-utf8-string-to-utf8-byte-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!