编写没有字节顺序标记(BOM)的文本文件? [英] Write text files without Byte Order Mark (BOM)?

查看:181
本文介绍了编写没有字节顺序标记(BOM)的文本文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用具有UTF8编码的VB.Net创建一个文本文件,而不需要BOM。有人可以帮我吗,怎么办?


我可以使用UTF8编码编写文件,但是如何从中删除字节订单?

I am trying to create a text file using VB.Net with UTF8 encoding, without BOM. Can anybody help me, how to do this?
I can write file with UTF8 encoding but, how to remove Byte Order Mark from it?

edit1:
我已经尝试过这样的代码;

edit1: I have tried code like this;

    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编码格式创建。

1.html get created with UTF8 encoding only and 2.html get created with ANSI encoding format.

简化方法 - http://whatilearnttuday.blogspot.com/2011/10/write-text-files-without-byte-order.html

推荐答案

为了省略字节顺序标记(BOM),您的流必须使用 UTF8Encoding 。 microsoft.com/en-us/library/system.text.encoding.utf8.aspxrel =noreferrertitle =MSDN参考页> System.Text.Encoding.UTF8 (配置为生成BOM)。有两种简单的方法可以做到这一点:

In order to omit the byte order mark (BOM), your stream must use an instance of UTF8Encoding other than System.Text.Encoding.UTF8 (which is configured to generate a BOM). There are two easy ways to do this:

1。明确指定合适的编码:


  1. 调用 UTF8Encoding 构造函数 encoderShouldEmitUTF8Identifier 参数的虚假

  1. Call the UTF8Encoding constructor with False for the encoderShouldEmitUTF8Identifier parameter.

传递 UTF8Encoding 实例到流构造函数。

Pass the UTF8Encoding instance to the stream constructor.



' 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。使用默认编码:

如果您不向 Encoding > StreamWriter 的构造函数, StreamWriter 将默认使用没有BOM的UTF8编码,因此以下内容也应该也是如此: p>

If you do not supply an Encoding to StreamWriter's constructor at all, StreamWriter will by default use an UTF8 encoding without BOM, so the following should work just as well:

' 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。

Finally, note that omitting the BOM is only permissible for UTF-8, not for UTF-16.

这篇关于编写没有字节顺序标记(BOM)的文本文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆