Follow in Twitter & Facebook


Like in Facebook

Powered By Blogger Widgets

Free Download

FREE Tools


Friday, July 28, 2017

Retrieve the exact site url from the ServerRelativeUrl in SharePoint online

We can retrieve the exact site url from the ServerRelativeUrl in SharePoint online using .Net managed object model code (C#.Net). Here we are doing in a console application and we are trying to connect to SharePoint online site.

Here my requirment is if the site url is: https://onlysharepoint2013.sharepoint.com/sites/Bhawana
It should return me onlu "Bhwana"

If the site url is https://onlysharepoint2013.sharepoint.com/sites/Bhawana/SubSite1

It should return me onlu "SubSite1"

Here in the GetSiteURL function we are taking the context and spliting the ServerRelativeUrl with "/" and returning the last element from the array.

Below is the full code:



 using (ClientContext context = new ClientContext(URL))
            {
                context.AuthenticationMode = ClientAuthenticationMode.Default;
                context.Credentials = new SharePointOnlineCredentials(GetSPOAccountName(), GetSPOSecureStringPassword());
                context.Load(context.Web, w => w.ServerRelativeUrl);
                context.Load(context.Web, w => w.Title);
                context.ExecuteQuery();
                string siteTitle = GetSiteURL(context);
}

 private static string GetSiteURL(ClientContext context)
        {
            string siteTitle;
            string[] strArray = context.Web.ServerRelativeUrl.Split('/');
            int j = strArray.Length;
            siteTitle = strArray[j - 1].ToString();
            return siteTitle;
        }

Hope this will be helpful.




0 on: "Retrieve the exact site url from the ServerRelativeUrl in SharePoint online"