How to properly validate file from user and detect extension change?

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?

Jon Skeet
people
quotationmark

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.

people

See more on this question at Stackoverflow