Check if file is a media file in C#

It depends how robust you want it to be.

The simplest way to do it is to check the extension, like this:

static string[] mediaExtensions = {
    ".PNG", ".JPG", ".JPEG", ".BMP", ".GIF", //etc
    ".WAV", ".MID", ".MIDI", ".WMA", ".MP3", ".OGG", ".RMA", //etc
    ".AVI", ".MP4", ".DIVX", ".WMV", //etc
};

static bool IsMediaFile(string path) {
    return -1 != Array.IndexOf(mediaExtensions, Path.GetExtension(path).ToUpperInvariant());
}

EDIT: For those who really want LINQ, here it is:

return mediaExtensions.Contains(Path.GetExtension(path), StringComparer.OrdinalIgnoreCase);

Note that a file's extension is not a reliable indicator of its content; anyone can rename a file and change its extension.

If you don't have the extension, or if you don't trust it, you can read the beginning of the file and see if it matches file signatures for common media formats.


Method 1: Easiest - File name parsing. If the filename matches a known list of media file types (i.e. jpg gif wmv avi mp4 etc), then it matches a video, audio, or image file. This is not as robust since I can easily name a text file with the extension .avi or .jpg, but that does not necessarily make it a media file.

Method 2: Harder - Parse file header. For example, at CodeProject there is a C# RIFF Parser or this CodeProject article on Extracting IPTC header information from JPEG images

You'll end up ultimately having to use a combination of both methods. Most of what you are asking is already built into the .NET framework.


Yes you can but unless you are using a component to do it you'll need to write code to at least load the headers of those files in order to check if they are not corrupted. If the files are stored in a reliable way, you can maybe just check its file extension

foreach(string file in Directory.GetFiles("c:\\MyDir\\")
{
   if(file.EndsWith("jpg", false, null))
      //treat as image file
   else if(file.EndsWith("avi", false, null))
      //treats as avi video
   //and so on
}

Tags:

C#