代码改变世界

清除UTF-8文件的BOM头

  胖子  阅读(3901)  评论(0编辑  收藏  举报

场景:

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

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

 

实现:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
/// <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;
}
1
注:时间有限,只考虑功能实现,没有考虑性能效率。
编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!
点击右上角即可分享
微信分享提示