Getting the absolute path in ASP.NET (part 2)

In a previous blog, I received many comments on various ways I could get the application root.  I am thankful for such comments.  What most of the commenters did not realize is that I need the resolution of the url in a custom http module, where Control.ResolveUrl is not practical to use.  And since I am using vanity urls (phantom paths that have no mapping to physical files or pages), I needed the resolution without the use of any System.IO objects.

However, I did make revisions to my method, and here it is:


1: public static string ResolveUrl(string url) 
2: {
3: if (url==null) throw new ArgumentNullException("url", "url can not be null");
4: if (url.Length == 0) throw new ArgumentException("The url can not be an empty string", "url");
5:
6: // there is no ~ in the first character position, just return the url
7: if (url[0] != '~') return url;
8:
9: string applicationPath = HttpContext.Current.Request.ApplicationPath;
10:
11: // there is just the ~ in the URL, return the applicatonPath
12: if (url.Length == 1) return applicationPath;
13:
14: // assume url looks like ~somePage
15: int indexOfUrl=1;
16:
17: // determine the middle character
18: string midPath = (applicationPath.Length >1 )? "/" : string.Empty;
19:
20: // if url looks like ~/ or ~\ change the indexOfUrl to 2
21: if (url[1] == '/' || url[1] == '\\') indexOfUrl=2;
22:
23: return applicationPath + midPath + url.Substring(indexOfUrl);
24: }// ResolveUrl
Any comments?


 

 

2 Comments

Comments have been disabled for this content.