Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

File Mime Type Checking

I am allowing uploading of files to my C# MVC website, I am restricting those types based on extension at the moment, but also feel I need a server side check to confirm they haven't just renamed it.

Is there a technique that I can use to check all the types I need or a library I can use that will help here?

I have seen people checking the first few bytes of the file, but I am scared I will miss something?

Thanks for your help.

Edit:

There are a lot of suggestions here. I will investigate some of these as a solution.

like image 583
shenku Avatar asked Nov 03 '22 16:11

shenku


2 Answers

If you are reading the file as an HttpPostedFile you can get the content type which is equal to the mime type.

So then you can do the following:

if (myFile.ContentType == "video/mpeg")
{
   // Do your thing
}
else{
   // error
}
like image 117
ffffff01 Avatar answered Nov 10 '22 00:11

ffffff01


Try this solution: Using .NET, how can you find the mime type of a file based on the file signature not the extension

It will do file content sniffing for you.

like image 22
Maksim Vi. Avatar answered Nov 10 '22 01:11

Maksim Vi.