判断文件类型

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

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图像文件,因为内容是空的,所以头两个字节根本获取不到,也就不能正确判断了。

项目完整代码

posted @ 2012-10-05 23:20  小凡(loveok_56)  阅读(1938)  评论(6编辑  收藏  举报