惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Y
Y Combinator Blog
V
V2EX
Jina AI
Jina AI
爱范儿
爱范儿
M
MIT News - Artificial intelligence
量子位
L
LangChain Blog
Google DeepMind News
Google DeepMind News
酷 壳 – CoolShell
酷 壳 – CoolShell
罗磊的独立博客
腾讯CDC
MongoDB | Blog
MongoDB | Blog
P
Proofpoint News Feed
宝玉的分享
宝玉的分享
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
Last Week in AI
Last Week in AI
H
Hackread – Cybersecurity News, Data Breaches, AI and More
F
Fortinet All Blogs
The GitHub Blog
The GitHub Blog
Engineering at Meta
Engineering at Meta
博客园 - 聂微东
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
Vercel News
Vercel News
T
The Blog of Author Tim Ferriss

博客园 - 胖子

Markdown Reader 插件改造 Visual Studio Code 使用心得 Philips K700 使用感受 XML、二进制、SOAP的序列化 powershell 相关 FireFox在windows2003的操作系统支持Windows Media Player插件 关于javascript编码url的中文参数 [转]IIS 6.0中配置HTTP Gzip压缩 数码相机在windows2003下的问题 MyGeneration连接MySql数据库的解决办法 一个简单的操作活动目录的类(ADHelper) SmartPhone下解决rm、rmvb等格式电影播放的方案(参考意见) 读写类似web.config的xml格式文件 - 胖子 - 博客园 Awstats 安装使用说明 关于博客园的聚合问题 关于保持页面滚动条位置的一些体会 胖子的故事(四) 胖子的故事(三) 胖子的故事(二)
清除UTF-8文件的BOM头
胖子 · 2010-01-20 · via 博客园 - 胖子

2010-01-20 13:42  胖子  阅读(3944)  评论()    收藏  举报

场景:

和某公司合作,给其提供xml文件。对方回邮件说:“你的文件是不是用写字板之类的编辑工具打开过?以二进制查看的时候文件头部有EF BB BF这3个字节……能否去掉?”

查阅了一些资料,发现这是windows系统自动添加的东西,而且调用.Net类库直接生成文件的方法,只要用utf-8编码,都会有这个东西。太无奈了,只好自己动手去掉这些了。

实现:

/// <summary>
/// 清除UTF8文件的BOM头
/// </summary>
/// <param name="filePath"></param>
/// <returns>是否成功</returns>
private static bool ClearBOM( string filePath )
{
	if( !CheckBOM( filePath ) )
		return true;

	string fileTemp = filePath + ".temp";

	using( FileStream fsRead = new FileStream( filePath, FileMode.Open ) )
	{
		// 跳过前三个字节
		fsRead.Seek( 3, SeekOrigin.Begin );
		int bufferSize = 1024;
		byte[] buffer = new byte[bufferSize];

		using( FileStream fsWrite = new FileStream( fileTemp, FileMode.Append, FileAccess.Write ) )
		{
			while( fsRead.Read( buffer, 0, bufferSize ) > 0 )
			{
				fsWrite.Write( buffer, 0, bufferSize );
			}
			fsWrite.Close();
		}
		fsRead.Close();
	}

	// 改名
	try
	{
		File.Delete( filePath );
		File.Move( fileTemp, filePath );
	}
	catch
	{
		return false;
	}
	return true;
}

/// <summary>
/// 检查是否有BOM头。
/// UTF8文件都有一个3字节的头,为“EF BB BF”(称为BOM--Byte Order Mark)
/// </summary>
/// <param name="filePath"></param>
/// <returns></returns>
private static bool CheckBOM( string filePath )
{
	bool isBOM = false;
	using( FileStream fsRead = new FileStream( filePath, FileMode.Open ) )
	{
		byte[] buffer = new byte[3];
		fsRead.Read( buffer, 0, 3 );
		if( 0xef == buffer[0] && 0xbb == buffer[1] && 0xbf == buffer[2] )
			isBOM = true;
		fsRead.Close();
	}
	return isBOM;
}
注:时间有限,只考虑功能实现,没有考虑性能效率。