Freigeben über


Using SharePoint OM to get the Default URL on a SharePoint Farm

How to get the Default port 80 URL on a SP Farm using the SP Object Model. This is useful if you're trying to run code on a Windows Front End (WFE) but don't know the SP Farm URL

Note that this code MUST run on a SP server front end.

                using Microsoft.SharePoint.Administration;              

                //
                // Check if we are on a SP server farm or not to get default server URL
                //
                SPFarm farm = SPFarm.Local; 

                 if (farm != null)
                {   

                    // Get the collection of all SP Alternate Urls        
                    SPAlternateUrlCollectionManager altUrlCollectionMgr = farm.AlternateUrlCollections;

                    // iterate thru collections of Urls
                    foreach (SPAlternateUrlCollection altColl in altUrlCollectionMgr)
                    {
                        foreach (SPAlternateUrl url in altColl)
                        {
                            // check if url is in Default zone
                            if (url.UrlZone == SPUrlZone.Default)
                            {
                                // get the port of the Uri and check for port 80
                                int UrlPortValue = url.Uri.Port;
                                if (UrlPortValue == 80)
                                {
                                    // set serverURL to Uri with port of 80
                                    this.serverURL = url.Uri.AbsoluteUri;
                                    // 
                                    return serverURL;
                                }
                            }
                        }
                    }