How do I check the file type of a file uploaded using FileUploader control in an ASP.NET C# webpage?
-
I tried checking file extension, but it obviously fails when a JPEG image (e.g.
Leonardo.jpg) is renamed to have a PDF’s extension (e.g.Leonardo.pdf). -
I tried
FileUpload1.PostedFile.ContentType.ToLower().Equals("application/pdf")but this fails as the above code behaves the same way as the first did.
Is there any other way to check the actual file type, not just the extension?
I looked at ASP.NET how to check type of the file type irrespective of extension.
Edit: I tried below code from one of the posts in stackoverflow. But this down’t work. Any idea about 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 });
}
}
Dont use File Extensions to work out MIME Types, instead use “Winista” for binary analysis.
Say someone renames an
exewith ajpgextension. You can still determine the real file format. It doesn’t detect swf’s or flv’s but does pretty much every other well known format and you can get a hex editor to add more files it can detect.Download Winista: here or my mirror or my GitHub https://github.com/MeaningOfLights/MimeDetect.
Where Winista fails to detect the real file format, I’ve resorted back to the URLMon method:
From inside the Winista method, I fall back on the URLMon here:
Update:
To work out more files using magic here is a FILE SIGNATURES TABLE