GeekZilla
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 .. } }
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?
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
phayman
said:
Great to hear from you Jav, email me at phayman@kwiboo.com
Regards,
Paul
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.
phayman
said:
Agreed, I've updated the article to include the RegexOptions.IgnoreCase switch
oburak
said:
RegexOptions.IgnoreCase => (int)RegexOptions.IgnoreCase
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
Juanjo
said:
It works just fine, Thanks dude
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.
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.