Click here to Skip to main content
15,851,711 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
There is a case in file upload,I have a image file and I am uploading that one is fine, and in other case have change the extension of .exe to png /jpeg , then how can we validate that file in this case.

What I have tried:

HttpPostedFile file = FileUpload1.PostedFile;
       byte[] document = new byte[file.ContentLength];
       file.InputStream.Read(document, 0, file.ContentLength);
       System.UInt32 mimetype;
       FindMimeFromData(0, null, document, 256, null, 0, out mimetype, 0);
       System.IntPtr mimeTypePtr = new IntPtr(mimetype);
       string mime = Marshal.PtrToStringUni(mimeTypePtr);

       if (mime == "application/pdf")
           // upload the File because file is valid // and checking other file type
           Response.Write("This is Valid File");
           //  file is Invalid
           Response.Write("This is Invalid File");

Mike Hankey 10-Sep-18 9:24am
Take a look at this site for a list of mime types.
MadMyche 10-Sep-18 13:12pm    
In the cases where it is not working, what is "FindMimeFromData" returning?

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900