I have encountered this piece of code that is supposed to determine the parent url in a hierarchy of dynamic (rewritten) urls. The basic logic goes like this:
"/testing/parent/default.aspx" --> "/testing/default.aspx"
"/testing/parent.aspx" --> "/testing/default.aspx"
"/testing/default.aspx" --> "/default.aspx"
"/default.aspx" --> null
...
private string GetParentUrl(string url)
{
string parentUrl = url;
if (parentUrl.EndsWith("Default.aspx", StringComparison.OrdinalIgnoreCase))
{
parentUrl = parentUrl.Substring(0, parentUrl.Length - 12);
if (parentUrl.EndsWith("/"))
parentUrl = parentUrl.Substring(0, parentUrl.Length - 1);
}
int i = parentUrl.LastIndexOf("/");
if (i < 2) return null;
parentUrl = parentUrl.Substring(0, i + 1);
return string.Format(CultureInfo.InvariantCulture, "{0}Default.aspx", parentUrl);
}
This code works but it smells to me. It will not work with urls that have a querystring. How can I improve it using regex?