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!

2 Answers 2


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("http://intranet.contoso.com/SubSite/PublicDocuments/Folder/SubFolder/");
ClientContext context = null;
if(TryResolveClientContext(requestUri, ref context, credentials))
     using (context)
        var folder = context.Web.GetFolderByServerRelativeUrl(requestUri.ToString());

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.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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