I am looping through a directory and copying all files. Right now I am doing string.EndsWith checks for ".jpg" or ".png", etc . .
Is there a more elegant way of determining if a file is an image (any image type) without the hacky check above?
I am looping through a directory and copying all files. Right now I am doing string.EndsWith checks for ".jpg" or ".png", etc . .
Is there a more elegant way of determining if a file is an image (any image type) without the hacky check above?
Check the file for a known header.
[Update: moving info out of comment]. The first eight bytes of a PNG file always contain the following (decimal) values: 137 80 78 71 13 10 26 10
Check out System.IO.Path.GetExtension
Here is a quick sample.
public static readonly List<string> ImageExtensions = new List<string> { ".JPG", ".JPE", ".BMP", ".GIF", ".PNG" };
private void button_Click(object sender, RoutedEventArgs e)
{
var folder = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
var files = Directory.GetFiles(folder);
foreach(var f in files)
{
if (ImageExtensions.Contains(Path.GetExtension(f).ToUpperInvariant()))
{
// process image
}
}
}
See if this helps.
EDIT: Also, Image.FromFile(....).RawFormat might help. It could throw an exception if the file is not an image.