5

I'm trying to get the top level site URL by using C# CSOM. i have site like below

 (http://test.sharepoint.com/aaa/bbbb) 

i am trying to get the rootWeb like below?

(http://test.sharepoint.com)

how do i get this?

Thank you in advance

1

You can use the Uri.DnsSafeHost property to get the root web of the tenant.

Modify the below mentioned sample code:

private string GetRootSite(string site)
{
    Uri uri = new Uri(site.TrimEnd(new[] { '/' }));

    // using old string.Format method
    // return string.Format("{0}://{1}",uri.Scheme,uri.DnsSafeHost);
    // or using the new $"{}" notation
    return $"{uri.Scheme}://{uri.DnsSafeHost}";
}

public void DoSomeStuff()
{   
    string siteUrl = "http://test.sharepoint.com/aaa/bbbb";
    string rootWebUrl = GetRootSite(siteUrl);
    //do some stuff with root web url
}

Reference - Uri.DnsSafeHost property

3

In .Net managed client code, you can use following method:

public static string GetRootweb()
{
    string rootweb = string.Empty;
    using (ClientContext context = new ClientContext("http://test.sharepoint.com/aaa/bbbb"))
    {
        context.AuthenticationMode = ClientAuthenticationMode.Default;
        context.Credentials = new SharePointOnlineCredentials(GetSPOAccountName(), GetSPOSecureStringPassword());
        context.Load(context.Site.RootWeb, w => w.Url, w => w.Title);
        context.ExecuteQuery();
        rootweb ="Root Web URL:: "+ context.Site.RootWeb.Url +" Title:: "+ context.Site.RootWeb.Title;             
    }
    return rootweb;
}

Note: GetSPOAccountName & GetSPOSecureStringPassword is the method to get user name and password to authenticate client context.

Here is the referral article.

0

You can use REST API to get to the root site. Try this below endpoint in your browser. Append this after your site URL -

 /_api/site/rootweb?$select=Title,ServerRelativeUrl,URL

To get just the URL, try this (specific to your example) -

http://test.sharepoint.com/aaa/bbbb/_api/site/rootweb?$select=URL

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.