Reputation: 139
I need a regular expression for C# to return a match for allowed paths and file names.
The following should match:
a
(at least one character)xxx/bbb.aspx
(path allowed and only .aspx extension is allowed)bbb.aspx?aaa=1
(querystring is allowed)It should not match for:
aaa.
aaa.gif
(only .aspx extension allowed)aaa.anythingelse
Upvotes: 1
Views: 1477
Reputation: 10361
.NET has built-in features for working with file paths, including finding file extensions. So I would strongly suggest using them instead of a regex. Here is a possible solution using System.IO.Path.GetExtension(). This is untested but it should work.
private static bool IsValid(string strFilePath)
{
//to deal with query strings such as bbb.aspx?aaa=1
if(strFilePath.Contains('?'))
strFilePath = strFilePath.Substring(0, strFilePath.IndexOf('?'));
//the list of valid extensions
string[] astrValidExtensions = { ".aspx", ".asp" };
//returns true if the extension of the file path is found in the
//list of valid extensions
return astrValidExtensions.Contains(
System.IO.Path.GetExtension(strFilePath));
}
Upvotes: 0