I don't want to rely on the file extension. I don't care to know what type of image it is (.jpg, .png, etc.), I simply want to know if the file is an image or not. I'd prefer to not use any non-.NET dlls if possible.
The best way I know how to do this is the following:
bool isImageFile;
try
{
Image.FromFile(imageFile).Dispose();
isImageFile = true;
}
catch (OutOfMemoryException)
{
isImageFile = false;
}
As noted here: http://msdn.microsoft.com/en-us/library/stf701f5.aspx, Image.FromFile()
throws an OutOfMemoryException
if the file isn't a valid image format. Using the above gives me exactly the result I want, however I'd prefer not to use it for the following reasons:
Image.FromFile()
loads the whole image file (if it is an image file) into memory. This is wasteful I assume because I only need the file type and don't need to do any further image manipulation at this point in my code.OutOfMemoryException
s because what if there is a REAL out-of-memory problem and my program swallows it and keeps going?Are there any better ways to do this? Or, are any/all of my concerns listed above unwarranted?
Edit: Since receiving the answers here, these are the three solutions I'm now aware of:
Image.FromFile()
and a try-catch.
(I do not see a clear "winner" since I can imagine a situation in which each one would be appropriate. For my application's purposes, the file type checking happens infrequently enough that the performance concerns of method 1 weren't an issue.)