如何确保我创建的文件下载为UTF-8? (而不是没有BOM的UTF-8) [英] How to make sure my created filedownload is UTF-8? (and not UTF-8 without BOM)
问题描述
我已经具有下载功能,可以将邮件下载到CSV文件(下面的代码)。
现在,当我在记事本或记事本++中打开它时,我会看到:
i've made a download function to download messages to a CSV file (code is below). Now when i open it up in notepad or notepad++ i see this:
éNYø╬►║êö
(这就是数据库btw中的内容)
(and that is what is in the database btw)
现在,当我在Ms-Excel中打开它时,它显示如下:
Now, when i open it up in Ms-Excel it shows this:
?NYÃââââââââââââââââö
é NY ø ╬ ║► ░ ê ö
当我在notepad ++中打开它,说它是用没有BOM的UTF8编码的。
当我(在记事本++中)将其编码为UTF-8时,一切都很好(即Excel也显示了正确的字符)
When i open it up in notepad++, it says it's encoded in 'UTF8 without BOM'. When i encode it (in notepad++) to UTF-8, all goes well (that is, Excel shows the right chars too)
但是我如何确保我从代码中创建的文件是UTF-8?
这是我的代码:
public ActionResult DownloadPersonalMessages()
{
StringBuilder myCsv = new StringBuilder();
myCsv.Append(new DownloadService().GetPersonalMessages());
this.Response.ContentType = "text/csv";
Response.AddHeader("content-disposition", "attachment; filename=PersonalMessages.csv");
Response.ContentEncoding = Encoding.UTF8;
Response.Write(myCsv.ToString());
Response.Flush();
Response.HeaderEncoding = Encoding.UTF8;
return Content("");
}
编辑:
我的函数现在通过此转换返回 ByteArray
my function now returns a ByteArray
with this conversion
UTF8Encoding encoding = new UTF8Encoding();
return encoding.GetBytes(str);
我的下载现在是这样:
Response.AddHeader("Content-Disposition", "attachment; filename=PersonalMessages.csv");
return File(new DownloadService().GetPersonalMessages(), "text/csv");
推荐答案
您可能想尝试使用 UTF8Encoding 类。构造函数具有一个参数,该参数确定是否应提供BOM。您可能必须使用GetBytes方法并将字符串作为一系列字节写入响应中,而不是将其转换回.net字符串对象。
You might want to try using the UTF8Encoding class. The constructor has a parameter that determines if it should provide the BOM or not. You'll probably have to use the GetBytes-method and write the string as a series of bytes in the response, and not convert it back into a .net string object.
这篇关于如何确保我创建的文件下载为UTF-8? (而不是没有BOM的UTF-8)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!