判断文件类型

看到网上好多判断文件类型的文章,所以就想自己动手实现,本文是根据文件流的头两个字节来判断,检测大概是什么图像。

View Code
 1         /// <summary>
 2         /// 判断文件类型
 3         /// </summary>
 4         /// <param name="filePath">文件路径</param>
 5         /// <param name="fileType">文件类型</param>
 6         /// <returns>真或假</returns>
 7         private static bool CheckFileType(string filePath, FileType fileType)
 8         {
 9 
10             int count = 2;
11             byte[] buf = new byte[count];
12             try
13             {
14                 using (StreamReader sr = new StreamReader(filePath))
15                 {
16                     if (count != sr.BaseStream.Read(buf, 0, count))
17                     {
18                         return false;
19                     }
20                     else
21                     {
22                         if (buf == null || buf.Length < 2)
23                         {
24                             return false;
25                         }
26 
27                         if (fileType.ToString() == Enum.GetName(typeof(FileType), ReadByte(buf)))
28                         {
29                             return true;
30                         }
31 
32                         return false;
33                     }
34                 }
35             }
36             catch (Exception ex)
37             {
38 
39                 Debug.Print(ex.ToString());
40                 return false;
41             }
42         }
View Code
 1         /// <summary>
 2         /// 把byte[]转换为int
 3         /// </summary>
 4         /// <param name="bytes">byte[]</param>
 5         /// <returns>int</returns>
 6         private static int ReadByte(Byte[] bytes)
 7         {
 8             StringBuilder str=new StringBuilder();
 9             for (int i = 0; i < bytes.Length; i++)
10             {
11                 str.Append(bytes[i]);
12             }
13 
14             return Convert.ToInt32(str.ToString());
15         }
View Code
 1     /// <summary>
 2     /// 文件类型
 3     /// </summary>
 4     public enum FileType
 5     {
 6         //TXT=100115,
 7         JPG=255216,
 8         PNG=13780,
 9         BMP=6677,
10         EXE=7790
11     }

备注:这种方法经测试有两点缺陷:

        1.不能正确判断文本文件,测试结果是每个txt文件得到的头两个字节都不一样

        2.若在桌面上右键新建一个空(0字节)的BMP图像文件,因为内容是空的,所以头两个字节根本获取不到,也就不能正确判断了。

项目完整代码

转载于:https://www.cnblogs.com/loveok-56/archive/2012/10/05/2712650.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值