判斷文件類型


看到網上好多判斷文件類型的文章,所以就想自己動手實現,本文是根據文件流的頭兩個字節來判斷,檢測大概是什么圖像。

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圖像文件,因為內容是空的,所以頭兩個字節根本獲取不到,也就不能正確判斷了。

項目完整代碼


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM