Check type of downloaded file

How to check the type of file loaded using the FileUploader control on an ASP.NET C # webpage?

  • I tried to check the file extension, but it obviously does not work when the JPEG image (e.g. Leonardo.jpg ) is renamed to the PDF extension (e.g. Leonardo.pdf ).

  • I tried

     FileUpload1.PostedFile.ContentType.ToLower().Equals("application/pdf") 

    but this fails because the code above behaves the same as the first.

Is there any other way to check the actual file type, not just the extension?

I looked at ASP.NET how to check file type regardless of extension .

Edit: I tried to execute code from one of the posts in stackoverflow. But that does not work. Any idea on this.

 /// <summary> /// This class allows access to the internal MimeMapping-Class in System.Web /// </summary> class MimeMappingWrapper { static MethodInfo getMimeMappingMethod; static MimeMappingWrapper() { // dirty trick - Assembly.LoadWIthPartialName has been deprecated Assembly ass = Assembly.LoadWithPartialName("System.Web"); Type t = ass.GetType("System.Web.MimeMapping"); getMimeMappingMethod t.GetMethod("GetMimeMapping", BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public)); } /// <summary> /// Returns a MIME type depending on the passed files extension /// </summary> /// <param name="fileName">File to get a MIME type for</param> /// <returns>MIME type according to the files extension</returns> public static string GetMimeMapping(string fileName) { return (string)getMimeMappingMethod.Invoke(null, new[] { fileName }); } } 
+3
source share
3 answers

Do not use File Extensions to develop MIME types, use "Winista" for binary analysis instead.

Let's say someone renames exe with the jpg extension. You can still determine the actual file format. It does not detect SWF or FLV, but works with almost all known formats, and you can get a hex editor to add more files that it can detect.

Download Winista: here or my mirror .

Where Winista cannot determine the actual file format, I resort to the URLMon method:

 public class urlmonMimeDetect { [DllImport(@"urlmon.dll", CharSet = CharSet.Auto)] private extern static System.UInt32 FindMimeFromData( System.UInt32 pBC, [MarshalAs(UnmanagedType.LPStr)] System.String pwzUrl, [MarshalAs(UnmanagedType.LPArray)] byte[] pBuffer, System.UInt32 cbSize, [MarshalAs(UnmanagedType.LPStr)] System.String pwzMimeProposed, System.UInt32 dwMimeFlags, out System.UInt32 ppwzMimeOut, System.UInt32 dwReserverd ); public string GetMimeFromFile(string filename) { if (!File.Exists(filename)) throw new FileNotFoundException(filename + " not found"); byte[] buffer = new byte[256]; using (FileStream fs = new FileStream(filename, FileMode.Open, FileAccess.Read)) { if (fs.Length >= 256) fs.Read(buffer, 0, 256); else fs.Read(buffer, 0, (int)fs.Length); } try { System.UInt32 mimetype; FindMimeFromData(0, null, buffer, 256, null, 0, out mimetype, 0); System.IntPtr mimeTypePtr = new IntPtr(mimetype); string mime = Marshal.PtrToStringUni(mimeTypePtr); Marshal.FreeCoTaskMem(mimeTypePtr); return mime; } catch (Exception e) { return "unknown/unknown"; } } } 

From within the Winista method, I return to URLMon here:

  public MimeType GetMimeTypeFromFile(string filePath) { sbyte[] fileData = null; using (FileStream srcFile = new FileStream(filePath, FileMode.Open, FileAccess.Read)) { byte[] data = new byte[srcFile.Length]; srcFile.Read(data, 0, (Int32)srcFile.Length); fileData = Winista.Mime.SupportUtil.ToSByteArray(data); } MimeType oMimeType = GetMimeType(fileData); if (oMimeType != null) return oMimeType; //We haven't found the file using Magic (eg a text/plain file) //so instead use URLMon to try and get the files format Winista.MimeDetect.URLMONMimeDetect.urlmonMimeDetect urlmonMimeDetect = new Winista.MimeDetect.URLMONMimeDetect.urlmonMimeDetect(); string urlmonMimeType = urlmonMimeDetect.GetMimeFromFile(filePath); if (!string.IsNullOrEmpty(urlmonMimeType)) { foreach (MimeType mimeType in types) { if (mimeType.Name == urlmonMimeType) { return mimeType; } } } return oMimeType; } 

Update:

For processing more files using magic, there is a table of file signatures

+5
source

Checking for names or extensions is not a reliable idea. The only way to make sure that you are really reading the contents of the file.

i.e. if you want to check the file for the image, try loading the image from the file, and if it failed, you can be sure that it is not an image file. This can be done easily using GDI objects.

The same is true for PDF files.

Conclusion: Do not rely on the user-supplied name or extension.

0
source

you can check the file type in FileApload on

ValidationExpression = "^ + (([pp] [dB] [Forward]) | ([Jj] [pp] [Gg]) | ([pp] [NN] [Gg])) ..) $"

for ex: you can add ([rR] [aA] [rR]) for the file type Rar, etc.

0
source

All Articles