您的位置:首页 > 其它

清除UTF-8文件的BOM头

2010-01-20 13:42 302 查看
场景:

和某公司合作,给其提供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;
}


注:时间有限,只考虑功能实现,没有考虑性能效率。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: