Finding the Site Directory

hey everyone, 

Well this is a relative quite easy assignment no? 

How can you find the site directory URL in SharePoint without laying a path to it hardcoded. 

Well the answer is, you’ll have to put the SiteDirectory url in the CentralAdmin (Operations -> Master Site Directory). 
To retrieve this information you’ll need some admin rights to get it. Ofcourse normal users don’t have these rights. So elevation is needed here. 

SPFarm farm = null;
                PortalService service = null;
                SPWebApplication app = null;
                string URL = SPContext.Current.Site.Url.ToString();
               SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                using (SPSite site = new SPSite(URL))
                {
                    System.Uri uri = new System.Uri(URL);
                    app = SPWebApplication.Lookup(uri);

                    farm = app.Farm;
                    foreach (SPService spservice in farm.Services)
                    {
                        if (spservice is PortalService)
                        {
                            service = spservice;
                            break;
                        }
                    }

                    GUID siteguid = new Guid(service.MasterSiteDirectorySiteId.ToString());
                    GUID webguid = new Guid(service.MasterSiteDirectoryWebId.ToString());

After this is it pretty easy, you’ll need to look for the “Sites” list et voila the rest is easy. 
The hard part was to figure out which service contains the information. And it appeared to be the PortalService. 

Hope this helps someone. 

Kind regards 
andy 

Leave a Reply

Your email address will not be published. Required fields are marked *