5

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.

Community
  • 1
  • 1
shenku
  • 9,802
  • 10
  • 57
  • 109
  • 1
    If all you got is a bunch of bytes, then I'm afraid it's going to be a bit difficult. If you're only dealing with images, you can always check for specific headers. – Etienne de Martel Sep 02 '12 at 05:47
  • it will be image types as well as other mime types such as doc, xls, pdfs etc. – shenku Sep 02 '12 at 05:48

5 Answers5

2

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
}
ffffff01
  • 4,259
  • 10
  • 48
  • 60
  • http://stackoverflow.com/questions/4019874/is-httppostedfile-contenttype-a-flawless-way-to-validate-an-uploaded-file – Maksim Vi. Sep 02 '12 at 10:35
0

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.

Community
  • 1
  • 1
Maksim Vi.
  • 8,589
  • 12
  • 54
  • 83
0

I ended up mixing some solutions from here, because I am not using the HttpFileBase and only have the file stream, I had to read the first few bytes of the stream to determine the mime type.

Note: I don't use the registry technique because I don't know what will or wont be installed on the servers.

Community
  • 1
  • 1
shenku
  • 9,802
  • 10
  • 57
  • 109
0

You can obtain the MIME type in the following way:

var fileName = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"');

                mimeType = file.ContentType;

Once MIME type is obtained, it can be compared with string comparison (as shown by @ffffff01 )

Abhay Shiro
  • 2,320
  • 2
  • 10
  • 23
0

For more safety you can also check both mimeType with the ContentType property as ffffff01 said, and file extension with Path.GetExtension method.