如何在 C# 中创建 UTF8 文件
根据问题,如何创建还包含字节顺序标记的文件?
显示某些字符时遇到一些问题,因为 csv 查看器在没有 BOM 的情况下无法正确显示字符。
感谢任何帮助。
编辑以包含代码:
string attachment = string.Format("attachment; filename=results_{0}_to _{1}.csv", startDate.ToString("MM_yy_yyyy"), endDate.ToString("MM_yy_yyyy"));
HttpContext.Current.Response.AddHeader("content-disposition", attachment);
HttpContext.Current.Response.ContentType = "text/csv";
HttpContext.Current.Response.AddHeader("Pragma", "public");
string content = GetTextFromDB();
HttpContext.Current.Response.Write(content);
HttpContext.Current.Response.End();
As per question how to i create a a file that also includes the Byte Order Mark?
Having some trouble displaying some chars because the csv viewer cannot display the chars correctly without the BOM.
Appreciate any help.
EDIT To Include code:
string attachment = string.Format("attachment; filename=results_{0}_to _{1}.csv", startDate.ToString("MM_yy_yyyy"), endDate.ToString("MM_yy_yyyy"));
HttpContext.Current.Response.AddHeader("content-disposition", attachment);
HttpContext.Current.Response.ContentType = "text/csv";
HttpContext.Current.Response.AddHeader("Pragma", "public");
string content = GetTextFromDB();
HttpContext.Current.Response.Write(content);
HttpContext.Current.Response.End();
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
对于使用
Encoding
的任何内置代码(例如StreamWriter
),这应该自动完成 - 只需确保您传入的编码器配置为包含 bom(默认Encoding.UTF8
包含 bom)。如果您正在处理自己的
Encoding
->Stream
逻辑,然后您需要调用.GetPreamble()
并在流的开头写入这些字节。默认的
Encoding.UTF8
包含前导码;但你可以在构造函数中显式地执行此操作:new UTF8Encoding(true)
This should be done automatically for any of the inbuilt code using an
Encoding
, such asStreamWriter
- just make sure that the encoder you pass in is configured to include a bom (the defaultEncoding.UTF8
includes the bom).If you are handling your own
Encoding
->Stream
logic, then you need to call.GetPreamble()
and write those bytes at the start of the stream.The default
Encoding.UTF8
includes the preamble; but you can do it explicitly in the ctor:new UTF8Encoding(true)