vb.net – 编写没有字节顺序标记(BOM)的文本文件?

我试图创建一个文本文件使用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",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的UTF8Encoding constructor
>将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("...");
}

最后,请注意,省略BOM仅允许使用UTF-8,而不允许使用UTF-16。

相关文章

Format[$] ( expr [ , fmt ] ) format 返回变体型 format$ 强...
VB6或者ASP 格式化时间为 MM/dd/yyyy 格式,竟然没有好的办...
在项目中添加如下代码:新建窗口来显示异常信息。 Namespace...
转了这一篇文章,原来一直想用C#做k3的插件开发,vb没有C#用...
Sub 分列() ‘以空格为分隔符,连续空格只算1个。对所选...
  窗体代码 1 Private Sub Text1_OLEDragDrop(Data As Dat...