c# 根據檔案流查看檔案真實格式

來源:互聯網
上載者:User

標籤:

    今天在做圖片註冊的功能的時候,測試提出一個問題:將隨便一個非圖片檔案將尾碼名改為jpg或其他,上傳時應檢驗圖片合法性。然後同事給提供了根據檔案流前兩個位元組判斷檔案真實格式的思路,代碼如下:

  public static FileExtension CheckFileType(string fileName)        {            FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);            System.IO.BinaryReader br = new System.IO.BinaryReader(fs);            string fileType = string.Empty; ;            try            {                byte data = br.ReadByte();                fileType += data.ToString();                data = br.ReadByte();                fileType += data.ToString();                FileExtension extension;                try                {                    extension = (FileExtension)Enum.Parse(typeof(FileExtension), fileType);                }                catch                 {                     extension = FileExtension.VALIDFILE;                }                return extension;            }            catch (Exception ex)            {                throw ex;            }            finally            {                if (fs != null)                {                    fs.Close();                    br.Close();                }            }        }
View Code

然後從網上找了各種檔案所對應的位元組關係如下:

  public enum FileExtension    {        JPG = 255216,        GIF = 7173,        BMP = 6677,        PNG = 13780,        COM = 7790,        EXE = 7790,        DLL = 7790,        RAR = 8297,        ZIP = 8075,        XML = 6063,        HTML = 6033,        ASPX = 239187,        CS = 117115,        JS = 119105,        TXT = 210187,        SQL = 255254,        BAT = 64101,        BTSEED = 10056,        RDP = 255254,        PSD = 5666,        PDF = 3780,        CHM = 7384,        LOG = 70105,        REG = 8269,        HLP = 6395,        DOC = 208207,        XLS = 208207,        DOCX = 208207,        XLSX = 208207,        VALIDFILE = 9999999    }

進行測試了一下,圖片格式都OK。

但是此方法不可以用於判斷視頻格式,不知走過路過的有木有較好的解決方案。

c# 根據檔案流查看檔案真實格式

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.