• 清除UTF8文件的BOM头


    场景:

    和某公司合作,给其提供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;
    }
    注:时间有限,只考虑功能实现,没有考虑性能效率。
  • 相关阅读:
    脚本 页面截取
    net Email 发送(借助第三方)
    查询表、存储过程、触发器的创建时间和最后修改时间(转)
    ActionScript简介
    mysql 1064 USING BTREE问题
    浅谈SQL SERVER函数count()
    程序员学习能力提升三要素
    构建杀手级应用的 JavaScript 框架、工具和技术
    javascript刷新页面方法大全
    html页<![if IE]>...<![endif]>使用解说
  • 原文地址:https://www.cnblogs.com/freemantc/p/1652321.html
Copyright © 2020-2023  润新知