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