09/11/2009

Uri Extension Method: AbsolutePathNoFile()

How often do you want to determine the absolute URI from any url without the specific file reference and without the query string variables. This is especially useful in many SharePoint tasks.

Here is a little extension method that can do just that. Pop this in a static class and try calling it on your Uri object:

public static UriExtensions {

public static string AbsolutePathNoFile(this Uri theUri)
{
string retVal = "http://" + theUri.Host + (theUri.Port == 80 ? "" : ":" + theUri.Port.ToString());
for (int intCnt = 0; intCnt < theUri.Segments.Length-1; intCnt++) {
retVal += theUri.Segments[intCnt];
}
return retVal;
}
}

// somewhere else:

Uri u = new Uri(Request.Url);
MessageBox.Show(u.AbsolutePathNoFile());

Over and Out

No comments: