SharePoint Stack Exchange is a question and answer site for SharePoint enthusiasts. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

Let's say the only input I have from the user is the full URL to a folder in a Document Library called "Public Documents":

Using the ClientContext constructor from the client object model, I can't pass it the full URL because it will say site not found under "SubFolder". I have to somehow parse the URL to pass either the site collection or the web "SubSite" to the ClientContext constructor to get a ClientContext.

What are some creative ways to parse the URL to get the CSOM objects from the URL string:

  • Site
  • Web
  • List
  • Folder

Thanks for your help!

share|improve this question

I'd generally start at the site collection level.

After the FQDN level there are a couple of options: a document library, a subsite or a managed path. If you can create a SPWeb from SubSite then you are good. From there you can look for a document library called PublicDocuments (lists tend to have /lists/ in the URL) and then find folders as described by the rest if the URL.

If you are unable to get an SPWeb from the SubSite part of the URL then you can try to get a document library object otherwise you know it's a a managed path and you can connect to the site site collection given by the URL up to the part after the managed path.

That's how I'd start.


share|improve this answer

The following method demonstrates how to resolve ClientContext by request Url:

private static bool TryResolveClientContext(Uri requestUri, ref ClientContext context, ICredentials credentials)
        var baseUrl = requestUri.GetLeftPart(UriPartial.Authority);
        for (int i = requestUri.Segments.Length; i >= 0; i--)
            var path = string.Join("", requestUri.Segments.Take(i));
            string url = string.Format("{0}{1}", baseUrl, path);
                context = new ClientContext(url);
                if(credentials != null)
                    context.Credentials = credentials;
                return true;
            catch (Exception ex) { }
        return false;


var requestUri = new Uri("");
ClientContext context = null;
if(TryResolveClientContext(requestUri, ref context, credentials))
     using (context)
        var folder = context.Web.GetFolderByServerRelativeUrl(requestUri.ToString());
share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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