You are not Logged in
Would you like to Login or Register

Today is: Friday, 21 November, 2008
Check this months hot topics

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 ..
    }
}
kick it on DotNetKicks.com del.icio.us digg Mister Wong YahooMyWeb Reddit Furl Spurl blogmarks
Paul Hayman Skype
Author : Paul Hayman
Published : Monday, 31 July, 2006

Paul is the COO of kwiboo ltd consultant and has more than a decade of 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?

November 27, 2006 - 9: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

June 26, 2007 - 3:30 PM

phayman said:

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

Regards,

Paul

June 26, 2007 - 3: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.

September 09, 2008 - 8:22 PM

phayman said:

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

September 09, 2008 - 9:17 PM

Add Comment

Enter your comment below and it will be submitted for moderation.

Your Name

Add Tag

Please enter tags for this article, seperated by semi-colon ;

View Tag's by : # articles | # views