StreamWriter和UTF-8字节顺序标记 [英] StreamWriter and UTF-8 Byte Order Marks

查看:71
本文介绍了StreamWriter和UTF-8字节顺序标记的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在StreamWriter和字节顺序标记方面遇到了问题。该文档似乎指出Encoding.UTF8编码已启用字节顺序标记,但是在写入文件时,有些带有标记,而其他则没有。

I'm having an issue with StreamWriter and Byte Order Marks. The documentation seems to state that the Encoding.UTF8 encoding has byte order marks enabled but when files are being written some have the marks while other don't.

我以以下方式创建流写入器:

I'm creating the stream writer in the following way:

this.Writer = new StreamWriter(this.Stream, System.Text.Encoding.UTF8);

对可能发生的事情的任何想法将不胜感激。

Any ideas on what could be happening would be appreciated.

推荐答案

正如已经指出的那样,没有编码参数的调用就可以解决问题。
但是,如果您想露骨,请尝试以下操作:

As someone pointed that out already, calling without the encoding argument does the trick. However, if you want to be explicit, try this:

using (var sw = new StreamWriter(this.Stream, new UTF8Encoding(false)))

关键是构造一个新的UTF8Encoding(false),而不是使用Encoding.UTF8Encoding。

The key is to construct a new UTF8Encoding(false), instead of using Encoding.UTF8Encoding. That's to control if BOM should be added or not.

这与不使用encoding参数调用StreamWriter相同,在内部它只是在做相同的事情。

This is the same as calling StreamWriter without the encoding argument, internally it's just doing the same thing.

这篇关于StreamWriter和UTF-8字节顺序标记的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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