Search code examples
c#file-uploadsharepoint-2016

Programatically target default document library for file upload in SP16


I made a C# application for uploading files to SharePoint. So far it Works as intended, on all document libraries except the default one. Everytime it throws an exception : List 'Documents' does not exist at site with URL 'http://...' I've tried with "Shared Documents" as well, but same result. Does the default library have some internal name I'm not aware of?

The code for uploading is as follows:

// Get the SharePoint context
            ClientContext context = new ClientContext(domain);

            // Open the web
            var web = context.Web;

            String[] files = System.IO.File.ReadAllLines(args[0]);

            foreach (String file in files)
            {
                // Create the new file  
                var newFile = new FileCreationInformation
                {
                    Content = System.IO.File.ReadAllBytes(file),
                    Url = Path.GetFileName(file),
                    Overwrite = true
                };

                // Get a reference to the document library
                var docs = web.Lists.GetByTitle(library);
                var uploadFile = docs.RootFolder.Files.Add(newFile);

                // Upload the document
                context.Load(uploadFile);
            }

Solution

  • First of all, it is much safer to get list by url, not title.

    using (ClientContext context = new ClientContext("https://sharepoint.domain.com"))
    {
        context.Load(context.Web, w => w.ServerRelativeUrl);
        context.ExecuteQuery();
    
        List list = context.Web.GetList($"{context.Web.ServerRelativeUrl.TrimEnd('/')}/Shared Documents");
    }
    

    Also don't forget to dispose the object context.

    Check enabled alternate languages (Site settings > Site Administration > Language settings). You may have more enabled languages and the default one could be different then you expect. Each language holds its own list name.