如何GetBytes会()在C#与BOM UTF8编码? [英] How to GetBytes() in C# with UTF8 encoding with BOM?

查看:501
本文介绍了如何GetBytes会()在C#与BOM UTF8编码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有在C#我的asp.net MVC 2应用程序使用UTF8编码的问题。我试图让用户从一个字符串下载一个简单的文本文件。我想获得的字节数组以下行:

I'm having a problem with UTF8 encoding in my asp.net mvc 2 application in C#. I'm trying let user download a simple text file from a string. I am trying to get bytes array with the following line:

VAR X = Encoding.UTF8.GetBytes(csvString);

但是当我使用返回它下载:

but when I return it for download using:

返回文件(X,...,...);

我得到一个文件,它是没有BOM,所以我没有得到露面的克罗地亚字符正确。这是因为编码后,我的字节数组不包括BOM。我triend手动插入这些字节,然后将它正确地显示了,但是这不是做到这一点的最好办法。

I get a file which is without BOM so I don't get Croatian characters shown up correctly. This is because my bytes array does not include BOM after encoding. I triend inserting those bytes manually and then it shows up correctly, but that's not the best way to do it.

我也尝试创建UTF8Encoding类的实例,并传递一个布尔值(true)给它的构造,包括BOM,但它不工作的。

I also tried creating UTF8Encoding class instance and passing a boolean value (true) to its constructor to include BOM, but it doesn't work either.

任何人有一个解决方案?谢谢!

Anyone has a solution? Thanks!

推荐答案

尝试这样的:

public ActionResult Download()
{
    var data = Encoding.UTF8.GetBytes("some data");
    var result = Encoding.UTF8.GetPreamble().Concat(data).ToArray();
    return File(result, "application/csv", "foo.csv");
}

究其原因是,UTF8Encoding构造函数的布尔参数不会做你所期望的:

The reason is that the UTF8Encoding constructor that takes a boolean parameter doesn't do what you would expect:

byte[] bytes = new UTF8Encoding(true).GetBytes("a");

结果数组将包含与97值的单字节有没有BOM,因为UTF8不需要BOM。

The resulting array would contain a single byte with the value of 97. There's no BOM because UTF8 doesn't require a BOM.

这篇关于如何GetBytes会()在C#与BOM UTF8编码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆