C# 如何将 utf8 字符串转换为 utf8 字节数组?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11539631/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 18:11:56  来源:igfitidea点击:

How to convert utf8 string to utf8 byte array?

c#.netencodingutf-8

提问by valch

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

如何将字符串转换为 utf8 字节数组,我有这个示例代码:

This works ok:

这工作正常:

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

This works wrong, file is in ASCII:

这是错误的,文件是 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();

采纳答案by Tigran

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

更多信息可以查看Encoding.UTF8 属性

回答by Qasim Javaid Khan

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

您只是想将 utf8string 转换为字节,这些文件流是做什么用的?

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