2

I am trying to send a file (Test.docx) to a specific folder under document library in sharepoint online. The folder name is "new" which is under a "Test" folder i.e. Documents/Test/new. Now, there could be additional subfolder under "new" folder where I want to send that file. I have tried with attached code, but it is not working. I can send file to "Test" folder with current code but not in subfolder of it in "new", and getting execption like "Microsoft.SharePoint.Client.ServerException: File Not Found". Is there a simple way to do that with my current code? Thank you!

            using (var clientContext = new ClientContext("https://myDomain.sharepoint.com/sites/siteName"))
            {
                clientContext.Credentials = new SharePointOnlineCredentials(username, securePassword)
            Web web = clientContext.Web;
            FileCreationInformation fileCreationInformation = new FileCreationInformation();
            fileCreationInformation.ContentStream = new MemoryStream(fileBytes);
            fileCreationInformation.Url = "Test.docx";  
            List documentLibrary = web.Lists.GetByTitle("Documents");  //get document library
            Folder destinationFolder = null;
            string destinationSubFolder = subFolder;  

            if (destinationSubFolder == "")
            {
                destinationFolder = documentLibrary.RootFolder;
            }
            else
            {
                destinationFolder = documentLibrary.RootFolder.Folders.GetByUrl("new"); 
                destinationFolder.Update();
            }

            Microsoft.SharePoint.Client.File uploadFile = destinationFolder.Files.Add(fileCreationInformation);

            clientContext.Load(documentLibrary);
            clientContext.Load(uploadFile);
            clientContext.ExecuteQuery();

        }

zam
  • 31
  • 1
  • 4

1 Answers1

1

Here is a simple with to generate the FileCreationInformation.Url with Path.Combine method:

                var uploadFilePath = "D:\\Test.docx";
                FileCreationInformation fileCreationInformation = new FileCreationInformation
                {
                    Content = System.IO.File.ReadAllBytes(uploadFilePath),
                    Url = System.IO.Path.Combine("Shared Documents/Test/New", System.IO.Path.GetFileName(uploadFilePath)),
                    Overwrite =true
            };

            var list = ctx.Web.Lists.GetByTitle("Documents");
            var uploadFile = list.RootFolder.Files.Add(fileCreationInformation);
            ctx.Load(uploadFile);
            ctx.ExecuteQuery();

The default "Documents" library should use "Shared Documents" as path.

Reference:

How to upload a file in a Sharepoint library subfolder using c#?

Jerry
  • 2,583
  • 1
  • 11
  • 11