I am new to SharePoint development, so forgive me if I am asking stupid questions. I have spent quite some time searching the web without success, so I am hoping to find an answer here.

Within a .NET Windows Forms application, I am trying to download (and later sync) a folder including subfolders from a SharePoint given the URL of the folder (e.g. https://mysharepoint/dummy1/dummy2/dummy3/myfolder) using CSOM. Target SharePoint versions are 2010 and 2013 (although it would be interesting to know how to do the same in 2007).

Looking at the URL, I can't really tell which part refers to a site, document library or folder within a document library. Fact is, this URL will later on be specified by the end user and will reference the end user's SharePoint, so I really don't know anything about the structure of the SharePoint.

So here are my questions:

  1. How do I get the right url for the ClientContext constructor?
  2. How do I get a reference to myfolder so I can iterate through files and subfolders?

Any hints on the right approach or even code samples will be greatly appreciated.

1 Answer 1


Ok, I solved it as follows (inspired by this post) - might be helpful for someone else...

The idea is to start from the back, removing more and more tokens between '/' from the path until we find the lowest level site URL, which we then use to instantiate the correct ClientContext for the given folder url. The folder itself can then be referenced using GetFolderByServerRelativeUrl(), but be aware that the argument is relative to the server, not relative to the site.

private bool GetSharePointContextAndFolderByUrl(string url, ref ClientContext context, ref Folder folder)
  Uri uri = new Uri(url);

  string[] tokens = uri.AbsolutePath.Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries);

  for (int i = tokens.Length; i >= 0; i--)
    string absUrl = string.Join("/", tokens.Take(i));
    string siteUrl = string.Format("{0}{1}{2}/{3}", uri.Scheme, Uri.SchemeDelimiter, uri.Host, absUrl);
    ClientContext c = null;
      c = new ClientContext(siteUrl);
      Folder f = c.Web.GetFolderByServerRelativeUrl(uri.AbsolutePath);
      context = c;
      folder = f;
      return true;
    catch (Exception e) { }
    if (c != null) c.Dispose();
  return false;

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.