1

I have this code

public bool IsImage(HttpPostedFileBase file)
{
    var contentType = file.ContentType.Split("/")(0).ToLower() == "image"

    if (contentType != "image")
    {
         return false;
    }

    return true;
}

however if the user rename an .exe file to .jpg, it will still think it is a valid image file. How to prevent this?

tickwave
  • 3,335
  • 6
  • 41
  • 82
  • possible duplicate of [How to find if a file is an exe?](http://stackoverflow.com/questions/2863683/how-to-find-if-a-file-is-an-exe) – Royi Namir Sep 29 '15 at 07:20

1 Answers1

4

The simplest way to check whether it's an image is to load it as an image, e.g. using Image.FromStream. If that throws an exception, it's not an image (or at least, not a supported image format). I'd trust that more than just using either the extension or the claimed MIME type.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • @RoyiNamir: The OP could certainly use the headers as a first pass - but again with the date handling, I'd prefer to use date parsing code than a regex for example, as it's much more likely to get all the rules for leap years right. (Of course I'd prefer to use an API which allowed me to try to parse *without* raising an exception for failure, but that's a slightly different matter.) Basically, a date parser, image loader or whatever is a piece of code designed precisely to judge whether or not the data is valid (and interpret it). Why use something less precise, other than as an initial pass? – Jon Skeet Sep 29 '15 at 07:37