压缩文件格式判定

本文介绍了一种通过读取文件头部特定字节来判断文件类型的简单方法。该方法能够识别ZIP、LZH和TGZ等压缩文件格式,并返回相应的类型标识。通过对文件头部几个字节的检查,可以快速确定文件是否属于这几种常见的压缩格式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

        public int GetFileType(string filePath)
        {
            int result = 0;

            if (File.Exists(filePath) == false)
            {
                return 0;
            }

            try
            {
                FileStream fs = new FileStream(filePath, FileMode.Open);
                int byteA = fs.ReadByte();                  //byte[0]
                int byteB = fs.ReadByte();                  //byte[1]
                fs.ReadByte();                              //byte[2]
                int byteC = fs.ReadByte();                  //byte[3]
                int byteD = fs.ReadByte();                  //byte[4]
                fs.Close();
                fs.Dispose();

                //ZIP:1
                if (byteA == 80 && byteB == 75)
                {
                    result = 1;
                }

                //LZH:2
                else if (byteC == 108 && byteD == 104)
                {
                    result = 2;
                }

                //TGZ:3
                else if (byteA == 31 && byteB == 139)
                {
                    result = 3;
                }

                //UNKNOWN:0
                else
                {
                    result = 0;
                }
            }
            catch
            {
                return 0;
            }

            return result;
        }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值