I need a method that could tell me if a file is image, audio or video file. Can I do this with C#?
-
1Point of clarification - you want to know whether it falls in *any* of the categories ("is a media file"), or *which* category it falls in ("is an image/is audio/is video")? – GalacticCowboy Dec 29 '09 at 16:59
-
It doesn't really make a difference. – SLaks Dec 29 '09 at 20:15
-
@SLaks: correct, it's pretty much just semantics but the solution would need to be slightly smarter than just a collection of extensions. It would have to map that extension to some higher-level meaning. – GalacticCowboy Jan 05 '10 at 18:14
6 Answers
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.

- 868,454
- 176
- 1,908
- 1,964
-
maybe people don't like string arrays? or maybe you could've used Contains ? i upvoted.. – Stan R. Dec 29 '09 at 16:32
-
-
mediaExtensions.Contains ... yes through LINQ..i don't know why someone downvoted, i was just throwing out ideas. like i said, i upvoted. – Stan R. Dec 29 '09 at 16:38
-
-
This may be a an okay first check until you get skmonone who encoded a mov as a avi or ogg as avi etc, check the file header e.g. probe an select the implementations which can likely service the files data – Jay Feb 08 '18 at 23:54
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.
-
The other problem with method 2 is that you have to have a parser for each file type, and other file types won't be recognized until you implement their parser... – GalacticCowboy Dec 29 '09 at 16:57
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
}

- 3,324
- 6
- 27
- 32
-
I think it should be a good practice to explain why the down vote. If what is expected is a simple naive implementation, the answer is very simple. But what if somebody change the extension of your files and messy up with their names? Do you believe in Santa Claws? – Andres Dec 29 '09 at 16:30
-
2i didn't downvote. but for starters not every extension will be lowercase, and imagine the kind of gigantic if statement this has to be to catch all media types.. – Stan R. Dec 29 '09 at 16:33
-
Ok, that's why EndsWith has a second parameter to tell to ignore character case. Now I think others answers should be down voted too as they are similar to mine in meaning – Andres Dec 29 '09 at 16:39
-
Apparently they were all downvoted (based on comments) even though everyone basically said the same thing and are all correct. Maybe somebody didn't want to hear the answer that was given? – GalacticCowboy Dec 29 '09 at 17:02
This code verifies whether a file is a media file. mediaExtensions
an array of well-known media filename extensions. The combination of path.Substring
and path.IndexOf
methods extract the file extension. Then the Array.IndexOf
tells whether the extracted extension matches any elements of the mediaExtensions
array. If not, Array.IndexOf
returns -1
(not found), causing IsMediaFile
to return false
. Otherwise, Array.IndexOf
returns the array index of the matching extesion, meaning a media file extension was found and IsMediaFile
returns true
.
Private Shared Function IsMediaFile(ByVal path As String) As Boolean
Try
Dim mediaExtensions As String() = {".PNG", ".JPG", ".JPEG", ".BMP", ".GIF", ".WAV", ".MID", ".MIDI", ".WMA", ".MP3", ".OGG", ".RMA", ".AVI", ".MP4", ".DIVX", ".WMV"}
Return -1 <> Array.IndexOf(mediaExtensions, path.Substring(path.IndexOf("."), path.Length - path.IndexOf(".")).ToUpper)
Catch ex As Exception
Throw ex
End Try
End Function

- 7,501
- 7
- 41
- 60
-
-
Generally, answers are much more helpful if they include an explanation of what the code is intended to do, and why that solves the problem without introducing others. – DCCoder Sep 28 '20 at 18:47
public static class CheckContentImage
{
public const int ImageMinimumBytes = 512;
public static bool IsImage(this IFormFile postedFile)
{
if (postedFile==null)
{
return false;
}
//-------------------------------------------
// Check the image mime types
//-------------------------------------------
if (postedFile.ContentType.ToLower() != "image/jpg" &&
postedFile.ContentType.ToLower() != "image/jpeg" &&
postedFile.ContentType.ToLower() != "image/pjpeg" &&
postedFile.ContentType.ToLower() != "image/gif" &&
postedFile.ContentType.ToLower() != "image/x-png" &&
postedFile.ContentType.ToLower() != "image/png")
{
return false;
}
//-------------------------------------------
// Check the image extension
//-------------------------------------------
if (Path.GetExtension(postedFile.FileName).ToLower() != ".jpg"
&& Path.GetExtension(postedFile.FileName).ToLower() != ".png"
&& Path.GetExtension(postedFile.FileName).ToLower() != ".gif"
&& Path.GetExtension(postedFile.FileName).ToLower() != ".jpeg")
{
return false;
}
//-------------------------------------------
// Attempt to read the file and check the first bytes
//-------------------------------------------
try
{
if (!postedFile.OpenReadStream().CanRead)
{
return false;
}
if (postedFile.Length < ImageMinimumBytes)
{
return false;
}
byte[] buffer = new byte[512];
postedFile.OpenReadStream().Read(buffer, 0, 512);
string content = System.Text.Encoding.UTF8.GetString(buffer);
if (Regex.IsMatch(content, @"<script|<html|<head|<title|<body|<pre|<table|<a\s+href|<img|<plaintext|<cross\-domain\-policy",
RegexOptions.IgnoreCase | RegexOptions.CultureInvariant | RegexOptions.Multiline))
{
return false;
}
}
catch (Exception)
{
return false;
}
//-------------------------------------------
// Try to instantiate new Bitmap, if .NET will throw exception
// we can assume that it's not a valid image
//-------------------------------------------
try
{
}
catch (Exception)
{
return false;
}
return true;
}
}

- 27
- 4
You can always check for the file extension.

- 26,396
- 5
- 54
- 57
-
Why was this downvoted? It's a perfectly acceptable answer though it is missing a code sample. – Thomas Aug 10 '16 at 15:59
-
@Thomas: the score's say that this is an edge case, which seems valid: `Any answer that gets the asker going in the right direction is helpful, but do try to mention any limitations, assumptions or simplifications in your answer. Brevity is acceptable, but fuller explanations are better.` https://stackoverflow.com/help/how-to-answer – Stefan Oct 18 '17 at 10:34