不带BOM创建文本文件

78

我尝试了这种方法,但没有成功。

我正在使用的代码:

// 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();

结果:

enter image description here

无论如何,都需要编写BOM,特殊字符(例如Æ Ø Å)不正确 :-/

我卡住了!

我的目标是使用UTF-8作为编码方式,8859-1作为字符集创建文件。

这么难实现吗?还是我今天运气不好?

非常感谢您的所有帮助,谢谢!


7
“使用UTF-8作为编码和8859-1作为字符集的文件”:编码和字符集是相同的概念,因此您的要求没有意义。 - Thomas Levesque
2个回答

194

因为你在代码中明确地指示要写入BOM,所以它才会写入BOM,这就是代码中这行语句的作用:

Encoding utf8WithoutBom = new UTF8Encoding(true);

true 表示应该使用 BOM 进行输出。

Encoding utf8WithoutBom = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false);

不添加 BOM。

我的目标是使用 UTF-8 作为编码和 8859-1 作为字符集创建一个文件。

可悲的是,这是不可能的,你要么写 UTF-8,要么不写。也就是说,只要你要写的字符存在于 ISO Latin-1 中,它看起来就像一个 ISO 8859-1 文件,但是一旦你输出了一个不受 ISO 8859-1 覆盖的字符(例如 ä,ö,ü),这些字符将被写成多字节字符。

要编写真正的 ISO-8859-1,请使用:

Encoding isoLatin1Encoding = Encoding.GetEncoding("ISO-8859-1");

编辑: 根据 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();

文件看起来完好无损。显然,在读取文件时应该使用相同的编码方式


7
MSDN提到了“EMIT”,我不小心读成了“OMIT”!我尝试使用编码方式"ISO-8859-1",但它并不会写BOM。但我仍然遇到了有关特殊字符的问题 :( - balexandre
1
@balexandre:我读了Ømit。你忘记让HttpResponse.Charset属性与文件的编码匹配了。将它们都设置为UTF-8是个好主意。 - Hans Passant
@Thomas Levesque 我误点了踩的按钮...(今天手指头点多了!而且...在踩的时候没有确认信息) :-/ 不过这是我的错!我很快就点了赞成 +1。 - balexandre
@nobugz HttpResponse与文件无关,文件已经写好,HttpResponse只是将其发送给客户端的部分。 - balexandre
@balexandre:没错,TransmitFile 会将其作为响应的一部分。所有响应中的文本必须具有相同的编码。 - Hans Passant

-2

Encoding.UTF8 不起作用。使用 Encoding.GetEncoding("iso-8859-1") 可以适用于所有类型的编码。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接