bal*_*dre 51 c# byte-order-mark asp.net-3.5 text-files
我试过这个方法没有任何成功
我正在使用的代码:
// 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();
Run Code Online (Sandbox Code Playgroud)
结果:

无论如何都在编写BOM,特殊字符(如ÆØÅ)不正确: - /
我被卡住了!
我的目标是使用UTF-8作为编码和8859-1作为CharSet 创建一个文件
难道这难以实现,或者我只是变得糟糕的一天?
非常感谢所有帮助,谢谢!
Axe*_*ger 125
好吧,它写了BOM,因为你在线上指示它
Encoding utf8WithoutBom = new UTF8Encoding(true);
Run Code Online (Sandbox Code Playgroud)
true 表示应使用发布BOM
Encoding utf8WithoutBom = new UTF8Encoding(false);
Run Code Online (Sandbox Code Playgroud)
没有写BOM.
我的目标是使用UTF-8作为编码和8859-1作为CharSet创建一个文件
可悲的是,这是不可能的,要么你写UTF-8,要么不写.即只要您正在编写的字符出现在ISO Latin-1中,它将看起来像ISO 8859-1文件,但是只要输出ISO 8859-1未涵盖的字符(例如ä,ö, ü)这些字符将被写为多字节字符.
要写真正的ISO-8859-1使用:
Encoding isoLatin1Encoding = Encoding.GetEncoding("ISO-8859-1");
Run Code Online (Sandbox Code Playgroud)
编辑:在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();
Run Code Online (Sandbox Code Playgroud)
该文件看起来非常好.显然,在读取文件时应该使用相同的编码.