Pedro77 Pedro77 - 1 year ago 102
C# Question

Good way to check if file extension is of an image or not

I have this file types Filters:

public const string Png = "PNG Portable Network Graphics (*.png)|" + "*.png";
public const string Jpg = "JPEG File Interchange Format (*.jpg *.jpeg *jfif)|" + "*.jpg;*.jpeg;*.jfif";
public const string Bmp = "BMP Windows Bitmap (*.bmp)|" + "*.bmp";
public const string Tif = "TIF Tagged Imaged File Format (*.tif *.tiff)|" + "*.tif;*.tiff";
public const string Gif = "GIF Graphics Interchange Format (*.gif)|" + "*.gif";
public const string AllImages = "Image file|" + "*.png; *.jpg; *.jpeg; *.jfif; *.bmp;*.tif; *.tiff; *.gif";
public const string AllFiles = "All files (*.*)" + "|*.*";

static FilesFilters()
imagesTypes = new List<string>();

OBS: Is there any default filters in .NET or a free library for that?

I need a static method that checks if a string is an image or not. How would you solve this?

//ext == Path.GetExtension(yourpath)
public static bool IsImageExtension(string ext)
return (ext == ".bmp" || .... etc etc...)

Solution using Jeroen Vannevel EndsWith. I think it is ok.

public static bool IsImageExtension(string ext)
return imagesTypes.Contains(ext);

Answer Source

You could use .endsWith(ext). It's not a very secure method though: I could rename 'bla.jpg' to 'bla.png' and it would still be a jpg file.

public static bool HasImageExtension(this string source){
 return (source.EndsWith(".png") || source.EndsWith(".jpg"));

This provides a more secure solution:

string InputSource = "mypic.png";
System.Drawing.Image imgInput = System.Drawing.Image.FromFile(InputSource);
Graphics gInput = Graphics.fromimage(imgInput);
Imaging.ImageFormat thisFormat = imgInput.rawformat;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download