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/mySite"))
{
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; //specify subfolder
if (destinationSubFolder == "")
{
destinationFolder = documentLibrary.RootFolder;
}
else
{
destinationFolder = documentLibrary.RootFolder.Folders.GetByUrl("new"); //when it is a subfolder
destinationFolder.Update();
}
Microsoft.SharePoint.Client.File uploadFile = destinationFolder.Files.Add(fileCreationInformation);
clientContext.Load(documentLibrary);
clientContext.Load(uploadFile);
clientContext.ExecuteQuery();
}