Using Regular Expressions to validate a filename in a FileUpload control

Here's a little code snippet I use to ensure that the file that has been uploaded is of type JPG, JPEG, PNG or GIF

// check anything has been uploaded
if (ThumbnailImageUpload.PostedFile.ContentLength > 0)
{
    // the regex for an image
    Regex imageFilenameRegex = new Regex(@"(.*?)\.(jpg|jpeg|png|gif)$");
 
    if (imageFilenameRegex.IsMatch(ThumbnailImageUpload.PostedFile.FileName, 
                            RegexOptions.IgnoreCase))
    {
        // we have a valid filename
        // .. do something ..
    }
}
Author Paul Hayman

Paul is the COO of kwiboo ltd and has more than 20 years IT consultancy experience. He has consulted for a number of blue chip companies and has been exposed to the folowing sectors: Utilities, Telecommunications, Insurance, Media, Investment Banking, Leisure, Legal, CRM, Pharmaceuticals, Interactive Gaming, Mobile Communications, Online Services.

Paul is the COO and co-founder of kwiboo (http://www.kwiboo.com/) and is also the creator of GeekZilla.

Comments

Ian Howie said:

The regex given will match (admittedly pathological) filenames like abc.jpg.def

Why not use the simpler @"\.(jpg|jpeg|png|gif)$" which my VERY limited knowledge of regular expressions tells me looks for one of the extensions at the end of a string?

27/Nov/2006 09:31 AM

Jav Ainesaz said:

Thanks Paul, The Regex expression was useful.

I wonder if you recognise my name (Smart421, London Gazette).

It was a pleasant surprise to do a Google search on Regex and come across your picture.

Regards

Jav

26/Jun/2007 15:30 PM

phayman said:

Great to hear from you Jav, email me at phayman@kwiboo.com

Regards,

Paul

26/Jun/2007 15:34 PM

jay said:

I dont think this will validate if a file has an extension .JPG or .GIF or any extension with capitals for that matter.

09/Sep/2008 20:22 PM

phayman said:

Agreed, I've updated the article to include the RegexOptions.IgnoreCase switch

09/Sep/2008 21:17 PM

oburak said:

 RegexOptions.IgnoreCase =>  (int)RegexOptions.IgnoreCase
22/Jul/2009 22:02 PM

nutan said:

is there any property of fileupload control which we can set in design mode which restric user to insert invalid extensions. pls reply

03/Jan/2010 08:54 AM

Juanjo said:

It works just fine, Thanks dude

05/Aug/2010 16:43 PM

M said:

It does NOT work correctly. It validates files like CSVTEST.EXE or CSVTEXT.BAT as well...

This is a serious problem when uploading files on a server.

04/Nov/2010 20:13 PM

SC said:

This code is potentially very dangerous. It allows paths to be submitted - for example - "..\..\..\blah.gif" would be successfully validaded. As would device names.

18/May/2012 20:31 PM

Add Comment

Name
Comment
 

Your comment has been received and will be shown once it passes moderation.