首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >是否写入不带字节顺序标记(BOM)的文本文件?

是否写入不带字节顺序标记(BOM)的文本文件?
EN

Stack Overflow用户
提问于 2010-03-13 15:43:26
回答 6查看 86K关注 0票数 119

我正在尝试创建一个文本文件使用VB.Net与UTF8编码,没有物料清单。有没有人能帮我,怎么做?

我可以写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()

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

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

EN

回答 6

Stack Overflow用户

发布于 2010-05-07 20:18:24

试试这个:

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
票数 29
EN

Stack Overflow用户

发布于 2015-06-24 04:46:15

如果在创建新的StreamWriter时没有指定Encoding,那么使用的默认Encoding对象是通过new UTF8Encoding(false, true)创建的UTF-8 No BOM

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

new StreamWriter(Stream)
new StreamWriter(String)
new StreamWriter(String, Boolean)
票数 4
EN

Stack Overflow用户

发布于 2013-11-27 19:15:04

我认为罗曼·尼基廷是对的。构造函数参数的含义颠倒了。False表示没有BOM,true表示有BOM。

您可以使用ANSI编码,因为没有BOM且不包含非ANSI字符的文件与ANSI文件完全相同。在您的"hi there“字符串中尝试一些特殊字符,您将看到ANSI编码更改为without-BOM。

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/2437666

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档