Click here to Skip to main content
15,902,447 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Given a document url of a sharepoint online document eg ""

I need to find the subsite url programmatically i.e " "

I am given with Root site Url and its credentials for Context:

using (ClientContext cContext = new ClientContext(""))
           cContext.Credentials = BuildCreds();

           Site s = cContext.Site;
           Web web = cContext.Site.OpenWeb("/sites/Site1/SubSite1/");  //i need to use in this method as  i need to load document from subsite

What I have tried:

I was trying to fetch url using position of "/ " but that fails when there are folders in document library.
Updated 11-Mar-20 23:39pm

1 solution

i have managed to get solution for this

public static void GetWebUrl()

            string fileUrl ="";
            Uri fileUri = new Uri(fileUrl);

            ClientContext rootContext = new ClientContext(fileUri.Scheme + Uri.SchemeDelimiter + fileUri.Host);
            Uri webUrl = Web.WebUrlFromPageUrlDirect(rootContext, fileUri);

            ClientContext subContext = new ClientContext(webUrl.ToString());

Share this answer
Richard Deeming 12-Mar-20 7:57am    
You can replace:
fileUri.Scheme + Uri.SchemeDelimiter + fileUri.Host

Uri.GetLeftPart(UriPartial) Method (System) | Microsoft Docs[^]

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900