3

我正在尝试在 HTTP 响应中发送一些在 Windows 1252 中编码的数据(它是一个 CSV 文件),但在某个地方它被重新编码为 UTF-8(无 BOM)。如何确保数据保持正确的编码?

var sb = new StringBuilder();
// Build the file from windows-1252 strings in the sb...
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.ClearHeaders();
HttpContext.Current.Response.ClearContent();
HttpContext.Current.Response.AddHeader("content-disposition", string.Format("filename=\"{0}\".csv", fileName));
HttpContext.Current.Response.ContentType = "text/csv;charset=windows-1252";
HttpContext.Current.Response.Charset = "windows-1252";
HttpContext.Current.Response.Write(sb.ToString());
HttpContext.Current.Response.Flush();
HttpContext.Current.Response.End();
4

1 回答 1

5

你打电话时

HttpContext.Current.Response.Write(someString)

输入someString将采用 .NET 的内部字符串表示形式(实际上是 UTF-16)。要实际发送输出,必须对其进行转换。默认情况下,此转换将转换为 UTF-8(因为它有效地支持整个 Unicode)。

Charset属性只是设置 HTTP 响应标头。但并不是还有一个ContentEncoding属性可以实际控制字符串的发送方式。

所以你失踪了

HttpContext.Current.Response.ContentEncoding = Encoding.GetEncoding("Windows-1252")

System.Text.Encoding有关支持的编码列表,请参阅 的描述。

于 2014-04-24T10:31:31.327 回答