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 any more elegant way of determining if a file is an image (any image type) without the hacky check like above?
If you are having trouble and want to check if you photo is a JPEG, look at the writing under the photo in its file name. If it ends . jpg or . jpeg- then the file is a JPEG and will upload.
Open a file in a Hex editor (or just a binary file viewer). PNG files start with 'PNG', . jpg files should have 'exif'or 'JFIF' somewhere in the beginning.
Check the file for a known header. (Info from link also mentioned in this answer)
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 } } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With