Search code examples
c#sharepointsharepoint-2010sharepoint-clientobject

Get document libraries in SharePoint WebSite


I need to use sharepoint client api in my project and list documents in folders that uploaded to sharepoint. My folders are under the link "https://mydomain.sharepoint.com/sites/blsmtekn/dyncrm/Shared%20Documents/Forms/AllItems.aspx"

        using (ClientContext ctx = new ClientContext("https://mydomain.sharepoint.com/"))
        {   
            string userName = "username";
            string password = "password";

            SecureString secureString = new SecureString();
            password.ToList().ForEach(secureString.AppendChar);

            ctx.Credentials = new SharePointOnlineCredentials(userName, secureString);

            List list = ctx.Web.Lists.GetByTitle("/Shared Documents/");
            CamlQuery caml = new CamlQuery();
            caml.ViewXml = @"<View Scope='Recursive'>
                                <Query>
                                </Query>
                            </View>";
            caml.FolderServerRelativeUrl = "/sites/blsmtekn/dyncrm/";
            ListItemCollection listItems = list.GetItems(caml);
            ctx.Load(listItems);
            ctx.ExecuteQuery();
        }

But I'm getting error like “List…does not exist at site with URL”. How can I get list of folders and files under that folders recursively.


Solution

  • From the top of my head I'm seeing a few mistakes: Your code states, that the name of your library is /Shared Documents/, while the name most likely is Shared Documents.

    Please fix the name of your GetByTitle() call:

    List list = ctx.Web.Lists.GetByTitle("Shared Documents");
    

    The second error is, that the url to your site collection is wrong. It should be

    ClientContext ctx = new ClientContext("https://mydomain.sharepoint.com/sites/blsmtekn/dyncrm/")
    

    Additionally you can remove caml.FolderServerRelativeUrl = "/sites/blsmtekn/dyncrm/"; since that is wrong.

    All in all your code should look like this:

    using (ClientContext ctx = new ClientContext("https://mydomain.sharepoint.com/sites/blsmtekn/dyncrm/"))
    {   
        string userName = "username";
        string password = "password";
    
        SecureString secureString = new SecureString();
        password.ToList().ForEach(secureString.AppendChar);
    
        ctx.Credentials = new SharePointOnlineCredentials(userName, secureString);
    
        List list = ctx.Web.Lists.GetByTitle("Shared Documents");
        CamlQuery caml = new CamlQuery();
        caml.ViewXml = @"<View Scope='Recursive'>
                            <Query>
                            </Query>
                        </View>";
        ListItemCollection listItems = list.GetItems(caml);
        ctx.Load(listItems);
        ctx.ExecuteQuery();
    }