我正在尝试使用 VB.Net 创建一个文本文件,采用 UTF8 编码,不带 BOM。谁能帮我,该怎么做?
我可以使用 UTF8 编码写入文件,但是如何从中删除字节顺序标记?
编辑1: 我尝试过这样的代码;
Dim utf8 As New UTF8Encoding()
Dim utf8EmitBOM As New UTF8Encoding(True)
Dim strW As New StreamWriter("c:\temp\bom\1.html", True, utf8EmitBOM)
strW.Write(utf8EmitBOM.GetPreamble())
strW.WriteLine("hi there")
strW.Close()
Dim strw2 As New StreamWriter("c:\temp\bom\2.html", True, 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),您的流必须使用 UTF8Encoding
的实例除了 System.Text.Encoding.UTF8
(配置为生成 BOM)。有两种简单的方法可以做到这一点:
<强>1。显式指定合适的编码:
调用
UTF8Encoding
constructor使用False
作为encoderShouldEmitUTF8Identifier
参数。将
UTF8Encoding
实例传递给流构造函数。
' 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("...");
}
最后,请注意,仅 UTF-8 允许省略 BOM,UTF-16 不允许。
关于vb.net - 写入没有字节顺序标记 (BOM) 的文本文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2437666/