C # View file True format based on file stream

Source: Internet
Author: User

Today in the function of image registration, the test posed a problem: will be any non-image files will be renamed to JPG or other, upload should check the legitimacy of the picture. Then the colleague gives the idea of judging the file's true format according to the first two bytes of the file stream, the code is as follows:

   Public StaticFileExtension Checkfiletype (stringfileName) {FileStream FS=NewFileStream (FileName, FileMode.Open, FileAccess.Read); System.IO.BinaryReader BR=NewSystem.IO.BinaryReader (FS); stringFileType =string.            Empty;; Try            {                bytedata =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; }                returnextension; }            Catch(Exception ex) {Throwex; }            finally            {                if(FS! =NULL) {fs.                    Close (); Br.                Close (); }            }        }
View Code

And then from the Internet to find the various files corresponding to the byte relationship is as follows:

   Public enumfileextension {JPG=255216, GIF=7173, BMP=6677, PNG=13780, COM=7790, EXE=7790, DLL=7790, RAR=8297, ZIP=8075, the XML=6063, HTML=6033, the ASPX=239187, CS=117115, JS=119105, TXT=210187, the 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    }

After testing, the image format is OK.

However, this method can not be used to determine the video format, do not know the passing of the wood has a better solution.

C # View file True format based on file stream

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.