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

Vij*_*ade 115 vb.net encoding byte-order-mark file-handling

我正在尝试使用带有UTF8编码的VB.Net创建一个文本文件,没有BOM.任何人都可以帮助我,怎么做?
我可以用UTF8编码写文件但是,如何从中删除字节顺序标记?

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

    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()
Run Code Online (Sandbox Code Playgroud)

1.html仅使用UTF8编码创建,2.html使用ANSI编码格式创建.

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

sta*_*ica 199

为了省略字节顺序标记(BOM),您的流必须使用UTF8EncodingSystem.Text.Encoding.UTF8(配置为生成BOM)之外的实例.有两种简单的方法可以做到这一点:

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

  1. 调用UTF8Encoding构造函数FalseencoderShouldEmitUTF8Identifier参数.

  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
Run Code Online (Sandbox Code Playgroud)
// C#:
var utf8WithoutBom = new System.Text.UTF8Encoding(false);
using (var sink = new StreamWriter("Foobar.txt", false, utf8WithoutBom))
{
    sink.WriteLine("...");
}
Run Code Online (Sandbox Code Playgroud)

2.使用默认编码:

如果您根本不提供Encodingto StreamWriter的构造函数,StreamWriter默认情况下将使用不带BOM的UTF8编码,因此以下内容也可以正常工作:

' VB.NET:
Using sink As New StreamWriter("Foobar.txt")
    sink.WriteLine("...")
End Using
Run Code Online (Sandbox Code Playgroud)
// C#:
using (var sink = new StreamWriter("Foobar.txt"))
{
    sink.WriteLine("...");
}
Run Code Online (Sandbox Code Playgroud)

最后请注意,省略BOM仅允许UTF-8,而不是UTF-16.


小智 28

试试这个:

Encoding outputEnc = new UTF8Encoding(false); // create encoding with no BOM
TextWriter file = new StreamWriter(filePath, false, outputEnc); // open file with encoding
// write data here
file.Close(); // save and close it
Run Code Online (Sandbox Code Playgroud)


Joe*_*ang 6

只需简单地使用的方法WriteAllTextSystem.IO.File.

请检查File.WriteAllText中的示例.

此方法使用UTF-8编码而没有字节顺序标记(BOM),因此使用GetPreamble方法将返回空字节数组.如果需要在文件开头包含UTF-8标识符(如字节顺序标记),请使用UTA8编码的WriteAllText(String,String,Encoding)方法重载.

  • My 命名空间中的那个确实使用了 BOM (2认同)

JG *_* SD 5

Encoding如果在创建新对象时未指定,则使用的StreamWriter默认对象是通过创建的。EncodingUTF-8 No BOMnew UTF8Encoding(false, true)

因此,要创建不带 BOM 的文本文件,请使用不需要提供编码的构造函数:

new StreamWriter(Stream)
new StreamWriter(String)
new StreamWriter(String, Boolean)
Run Code Online (Sandbox Code Playgroud)