0

I am trying to determine the Mime Type of an uploaded file using C#. There are various methods to get the MIME type from the file extension (ContentType for the HttpPosted File, GetMimeMapping from the filename, etc). However all of these methods rely on the file name/extension.

This would allow a user to upload an unwanted file (like an .exe), by simply changing the extension of the file to an accepted extension (like .png). Since these methods determine the file type based on the extension, the exe would be passed off as a png image file.

I would like to be able to check the data in the file headers in order to determine the file type, instead of relying on filename. Are there are libraries or utilities which can help determine the file type by looking at the data/header instead of filenames and extensions?

Kevat Shah
  • 119
  • 1
  • 12
  • 1
    There's no standard for file headers. You have to know low-level details about every file type you're interested in. – Joel Coehoorn Mar 06 '18 at 15:45
  • Go research magic bytes. In short there's no bulletproof way, you just have to test each file type to see if it looks like what you want. Asking for libraries is off topic. – Equalsk Mar 06 '18 at 15:45
  • While the duplicate post does provide a solution, the answer posted by Vidmantas is much closer to what I was looking for. – Kevat Shah Mar 07 '18 at 17:38

1 Answers1

1

I've used Mime-detective (https://github.com/Muraad/Mime-Detective) in one of my projects. Does exactly what you are looking for and does not depend on file extensions.

Vidmantas Blazevicius
  • 4,652
  • 2
  • 11
  • 30
  • I've marked this post as a duplicate, but I think your answer is much better than the other one. Looks like you're solution is checking the headers and has the definitions for the headers of many commonly used file types. – Kevat Shah Mar 07 '18 at 17:37