vb.net – 编写没有字节顺序标记(BOM)的文本文件?
发布时间:2020-12-17 07:33:18 所属栏目:百科 来源:网络整理
导读:我试图创建一个文本文件使用VB.Net与UTF8编码,没有BOM。任何人都可以帮助我,怎么办? 我可以写文件用UTF8编码,但是,如何从它的字节顺序标记中删除? 编辑1: 我试过这样的代码; Dim utf8 As New UTF8Encoding() Dim utf8EmitBOM As New UTF8Encoding(Tru
我试图创建一个文本文件使用VB.Net与UTF8编码,没有BOM。任何人都可以帮助我,怎么办?
我可以写文件用UTF8编码,但是,如何从它的字节顺序标记中删除? 编辑1: Dim utf8 As New UTF8Encoding() Dim utf8EmitBOM As New UTF8Encoding(True) Dim strW As New StreamWriter("c:tempbom1.html",True,utf8EmitBOM) strW.Write(utf8EmitBOM.GetPreamble()) strW.WriteLine("hi there") strW.Close() Dim strw2 As New StreamWriter("c:tempbom2.html",utf8) strw2.Write(utf8.GetPreamble()) strw2.WriteLine("hi there") strw2.Close() 1.html用UTF8编码创建,2.html用ANSI编码格式创建。 简化方法 – http://whatilearnttuday.blogspot.com/2011/10/write-text-files-without-byte-order.html
为了省略字节顺序标记(BOM),您的流必须使用
System.Text.Encoding.UTF8 之外的
UTF8Encoding 实例(配置为生成BOM)。有两种简单的方法:
1.显式指定合适的编码: >为encoderShouldEmitUTF8Identifier参数调用带有False的 ' VB.NET: Dim utf8WithoutBom As New System.Text.UTF8Encoding(False) Using sink As New StreamWriter("Foobar.txt",False,utf8WithoutBom) sink.WriteLine("...") End Using // C#: var utf8WithoutBom = new System.Text.UTF8Encoding(false); using (var sink = new StreamWriter("Foobar.txt",false,utf8WithoutBom)) { sink.WriteLine("..."); } 2.使用默认编码: 如果你根本不给StreamWriter的构造函数提供一个Encoding,StreamWriter默认情况下会使用一个没有BOM的UTF8编码,所以下面的代码也应该工作: ' VB.NET: Using sink As New StreamWriter("Foobar.txt") sink.WriteLine("...") End Using // C#: using (var sink = new StreamWriter("Foobar.txt")) { sink.WriteLine("..."); } 最后,请注意,省略BOM仅允许使用UTF-8,而不允许使用UTF-16。 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |