Click here to Skip to main content
15,881,882 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Given a document url of a sharepoint online document eg " https://demo.sharepoint.com/sites/Site1/SubSite1/subsiteDocumentLib/DEMO_Doc.docx"

I need to find the subsite url programmatically i.e "https://demo.sharepoint.com/sites/Site1/SubSite1/ "

I am given with Root site Url and its credentials for Context: https://demo.sharepoint.com/sites/Site1/


using (ClientContext cContext = new ClientContext("https://demo.sharepoint.com/sites/Site1/"))
       {
           cContext.Credentials = BuildCreds();


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


What I have tried:

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

1 solution

i have managed to get solution for this

public static void GetWebUrl()
 {

            string fileUrl ="https://demo.sharepoint.com/sites/Site1/SubSite1/subsiteDocumentLib/DEMO_Doc.docx";
            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
 
Comments
Richard Deeming 12-Mar-20 7:57am    
You can replace:
fileUri.Scheme + Uri.SchemeDelimiter + fileUri.Host
with:
fileUri.GetLeftPart(UriPartial.Authority)

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