I tried 这种方法 https://stackoverflow.com/questions/2437666/write-text-files-without-byte-order-mark-bom没有任何成功
我正在使用的代码:
// File name
String filename = String.Format("{0:ddMMyyHHmm}", dtFileCreated);
String filePath = Path.Combine(Server.MapPath("App_Data"), filename + ".txt");
// Process
myObject pbs = new myObject();
pbs.GenerateFile();
// pbs.GeneratedFile is a StringBuilder object
// Save file
Encoding utf8WithoutBom = new UTF8Encoding(true);
TextWriter tw = new StreamWriter(filePath, false, utf8WithoutBom);
foreach (string s in pbs.GeneratedFile.ToArray())
tw.WriteLine(s);
tw.Close();
// Push Generated File into Client
Response.Clear();
Response.ContentType = "application/vnd.text";
Response.AppendHeader("Content-Disposition", "attachment; filename=" + filename + ".txt");
Response.TransmitFile(filePath);
Response.End();
结果:
It's 编写 BOM http://en.wikipedia.org/wiki/Byte_order_mark#Representations_of_byte_order_marks_by_encoding无论如何,以及特殊字符(如 Æ Ø Å)
不正确:-/
我被困住了!
我的目标是使用创建一个文件UTF-8作为编码和8859-1作为字符集
这是很难实现还是我今天过得很糟糕?
非常感谢所有帮助,谢谢!
好吧,它会写入 BOM,因为您指示它在该行中
Encoding utf8WithoutBom = new UTF8Encoding(true);
true
意味着应该发出 BOM,使用
Encoding utf8WithoutBom = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false);
不写入 BOM。
我的目标是使用 UTF-8 作为编码和 8859-1 作为字符集创建一个文件
遗憾的是,无论您是否编写 UTF-8,这是不可能的。 IE。只要您编写的字符存在于 ISO Latin-1 中,它看起来就像 ISO 8859-1 文件,但是一旦您输出 ISO 8859-1 未涵盖的字符(例如 ä、ö、ü )这些字符将被写为多字节字符。
要编写真正的 ISO-8859-1,请使用:
Encoding isoLatin1Encoding = Encoding.GetEncoding("ISO-8859-1");
Edit:balexandre发表评论后
我使用以下代码进行测试...
var filePath = @"c:\temp\test.txt";
var sb = new StringBuilder();
sb.Append("dsfaskd jlsadfj laskjdflasjdf asdkfjalksjdf lkjdsfljas dddd jflasjdflkjasdlfkjasldfl asääääjdflkaslj d f");
Encoding isoLatin1Encoding = Encoding.GetEncoding("ISO-8859-1");
TextWriter tw = new StreamWriter(filePath, false, isoLatin1Encoding);
tw.WriteLine(sb.ToString());
tw.Close();
该文件看起来非常好。明显地,读取文件时应该使用相同的编码.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)