Search code examples
c#sharepointcsom

Get a subfolder using SharePoint CSOM


I am wanting to get a folder within Shared Documents on a SharePoint site using CSOM in order to add files to it. Here is my current code:

        // Get the folder we want to add images to
        var context = new ClientContext(sharePointSiteUrl)
        context.Credentials = new SharePointOnlineCredentials(username, password);
        Web web = context.Web;
        Folder targetFolder = web.GetFolderByServerRelativeUrl("/Shared%20Documents/" + nameOfTargerFolder);
        context.ExecuteQuery();

And I am getting this error: "Server relative urls must start with SPWeb.ServerRelativeUrl"

Thanks so much!


Solution

  • The web object has a serverrelativeurl property: https://learn.microsoft.com/en-us/dotnet/api/microsoft.sharepoint.spweb.serverrelativeurl?view=sharepoint-server

    Try this:

        // Get the folder we want to add images to
        var context = new ClientContext(sharePointSiteUrl)
        context.Credentials = new SharePointOnlineCredentials(username, password);
        Web web = context.Web;
        context.Load(web, w => w.ServerRelativeUrl);
        context.ExecuteQuery();
        Folder targetFolder = web.GetFolderByServerRelativeUrl(web.ServerRelativeUrl + "/Shared%20Documents/" + nameOfTargerFolder);
        context.ExecuteQuery();