How to find the URL of a SharePoint web application given the url of a Site within that

Prabhu picture Prabhu · Oct 9, 2009 · Viewed 11.2k times · Source

I need to find the URL of the web application of a given Site (say I have an url http://code/sites/java. Given the url of this site collection i need the URL of the web app that hosts this site collection. In this case it will be http://code. ) Any input will be appreciated.

Answer

Alex Angas picture Alex Angas · Oct 9, 2009
  1. If you have an SPWeb object use its Site property. If you have an SPSite object use its WebApplication property. If you don't have either, create an SPSite object from that URL.

  2. From the SPWebApplication object use the AlternateUrls property.

  3. From the SPAlternateUrlCollection object retrieve the SPAlternateUrl for your desired zone.

  4. From the SPAlternateUrl object get the actual URL.

The reason why you need to go through the alternate URL collection is because of the alternate access mappings you can associate with a web application. For example all web apps start with Default, which can be extended to Intranet, Extranet, etc.

Remember to use dispose with the above objects as necessary.