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

标签 vb.net encoding file-handling byte-order-mark

我正在尝试使用 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。显式指定合适的编码:

  1. 调用UTF8Encoding constructor使用 False 作为 encoderShouldEmitUTF8Identifier 参数。

  2. 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 的构造函数提供 EncodingStreamWriter 将默认使用不带 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/

相关文章:

c# - Visual Studio 上的 "The File Exist"错误

python - python写文件处理编码

c - fscanf() fclose() 或读取文件退出并结束程序

java - 打印外部文件的内容

c# - 将文件夹重命名命令发送到 Windows 资源管理器

vb.net - 创建 UdpClient 来读取传入数据 - VB.net

c# - 为什么 InvokeRequired 和 Dispatcher.CheckAccess 的 bool 值颠倒?

php - 如何确定一个字符所需的最小字节数?

html - 使用 windows-1252 而不是 UTF-8 有什么问题

java - 如何从txt文件中根据最小数量获取5个项目