如何将utf8字符串转换为utf8字节数组? [英] How to convert utf8 string to utf8 byte array?
本文介绍了如何将utf8字符串转换为utf8字节数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何将字符串转换为utf8字节数组,我有以下示例代码:
How can I convert string to utf8 byte array, I have this sample code:
这行得通:
StreamWriter file = new StreamWriter(file1, false, Encoding.UTF8);
file.WriteLine(utf8string);
file.Close();
这是错误的,文件是ASCII:
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)
因为这样行得通:
byte[] datab = File.ReadAllBytes(file1);
FileStream fs2 = new FileStream(file3, FileMode.CreateNew);
fs2.Write(datab, 0, datab.Length);
fs2.Close();
推荐答案
可以再次使用其他选项:
Can use other option again:
string value = "\u00C4 \uD802\u0033 \u00AE";
byte[] bytes= System.Text.Encoding.UTF8.GetBytes(value);
有关更多信息,请参见 Encoding.UTF8属性
For more information can look on Encoding.UTF8 Property
这篇关于如何将utf8字符串转换为utf8字节数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文