In C# what is the best way to tell if a particular file is an image?
Most picture formats specify the file type in the first few bytes of the image. You can read in a few bytes and look for the correct headers.
File extensions technically don't hold any important data about the image. It just helps the OS figure out what program to use to open it. (But, checking the extn is probably the easiest way, and usually correct.)
This isn't tested, but it's something like this:
private string MimeType (string Filename)
{
string mime = "[default]";
string ext = GetExtension(Filename).ToLower();
Microsoft.Win32.RegistryKey rk = Microsoft.Win32.Registry.ClassesRoot.OpenSubKey(ext);
if (rk != null && rk.GetValue("Content Type") != null)
mime = rk.GetValue("Content Type").ToString();
return mime;
}
(Sorry, it's been awhile since I've done registry stuff)
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