利用檔案頭判斷檔案類型

來源:互聯網
上載者:User

上傳檔案時經常需要做檔案類型判斷,例片、文檔等,普通做法是直接判斷檔案尾碼名,而文藝青年為了防止各種攻擊同時也會加上使用檔案頭資訊判斷檔案類型。

原理很簡單:用檔案頭判斷,直接讀取檔案的前2個位元組即可。

Demo

using System;

using System.IO;

 

namespace HelloWorld

{

    class Program

    {

        static void Main(string[] args)

        {

            FileStream fs = new FileStream(@"C:\test.rar", FileMode.Open, FileAccess.Read);

            BinaryReader reader = new BinaryReader(fs);//轉換為二進位流

            byte[] buff = new byte[2];

            string result = string.Empty;

            try

            {

                fs.Read(buff, 0, 2);

                result = buff[0].ToString() + buff[1].ToString();

            }

            catch (Exception ex)

            {

                throw ex;

            }

 

            reader.Close();

            fs.Close();

 

            if (result == "8297")//rar:8297

            {

                Console.WriteLine("檔案格式是rar." + result);

            }

            else

            {

                Console.WriteLine("檔案格式不是rar." + result);

            }

            Console.ReadLine();

        }

    }

}

 

附常見檔案的檔案頭資訊

常見檔案的檔案頭(十進位)

jpg: 255,216

gif: 71,73

bmp: 66,77

png: 137,80

doc: 208,207

docx: 80,75

xls: 208,207

xlsx: 80,75

js: 239,187

swf: 67,87

txt: 70,67

mp3: 73,68

wma: 48,38

mid: 77,84

rar: 82,97

zip: 80,75

xml: 60,63

熱門檔案的檔案頭如下(16進位):

JPEG (jpg),檔案頭:FFD8FF

PNG (png),檔案頭:89504E47

GIF (gif),檔案頭:47494638

TIFF (tif),檔案頭:49492A00

Windows Bitmap (bmp),檔案頭:424D

CAD (dwg),檔案頭:41433130

Adobe Photoshop (psd),檔案頭:38425053

Rich Text Format (rtf),檔案頭:7B5C727466

XML (xml),檔案頭:3C3F786D6C

HTML (html),檔案頭:68746D6C3E

Email [thorough only] (eml),檔案頭:44656C69766572792D646174653A

Outlook Express (dbx),檔案頭:CFAD12FEC5FD746F

Outlook (pst),檔案頭:2142444E

MS Word/Excel (xls.or.doc),檔案頭:D0CF11E0

MS Access (mdb),檔案頭:5374616E64617264204A

WordPerfect (wpd),檔案頭:FF575043

Postscript (eps.or.ps),檔案頭:252150532D41646F6265

Adobe Acrobat (pdf),檔案頭:255044462D312E

Quicken (qdf),檔案頭:AC9EBD8F

Windows Password (pwl),檔案頭:E3828596

ZIP Archive (zip),檔案頭:504B0304

RAR Archive (rar),檔案頭:52617221

Wave (wav),檔案頭:57415645

AVI (avi),檔案頭:41564920

Real Audio (ram),檔案頭:2E7261FD

Real Media (rm),檔案頭:2E524D46

MPEG (mpg),檔案頭:000001BA

MPEG (mpg),檔案頭:000001B3

Quicktime (mov),檔案頭:6D6F6F76

Windows Media (asf),檔案頭:3026B2758E66CF11

MIDI (mid),檔案頭:4D546864

 

    

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.