How can I programmatically extract the site path from a given URL? The solution would have to be able to handle paths with multiple levels of sub sites. The number of sub site levels is also not always the same.

Here are two sample urls/examples and what I would like to get from them.

This one is two sub sites deep from the root site collection:


Output: http://intranet/corporate/finance

And one that is only one sub site deep:


Output: http://intranet/corporate

  • Will the URLs always point to a document in the library? – Mohit Mar 31 '15 at 12:22
  • Yes they will always be to a document held in a library. – Stuart C Mar 31 '15 at 12:26
  • Why not simply twice from last on '/' – Mohit Mar 31 '15 at 12:28
  • Why don't you simply sub-string from last twice on '/' – Mohit Mar 31 '15 at 12:29
  • That would work yes - thanks. I should have mentioned that some of the documents may also be inside document sets which would add another level to the URL. Any suggestions on how to handle this? – Stuart C Mar 31 '15 at 12:37

To answer my own question.

string fullUrl = "http://siteCollection/subsite/library/folder/document.docx"
string siteUrl = string.Empty;

using (SPSite site = new SPSite(fullUrl)) 
    SPWeb web = site.OpenWeb();
    siteUrl = web.Url;

This will take the full url path to a document and return the path to it's site, in this case http://siteCollection/subsite

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.