question

developersp1-9584 avatar image
0 Votes"
developersp1-9584 asked Jerryzy answered

CSOM - Upload a file to a subdirectory in Sharepoint Online

var uploadFile = list
.RootFolder
.Folders
.GetByPath(ResourcePath.FromDecodedUrl("A/B/C"))
.Files
.Add(newFile);

ctx.Load(uploadFile);
await ctx.ExecuteQueryAsync();

Throws System.IO.DirectoryNotFoundException even though both directories exist. So how can I upload a file to the subdirectory "C" under A/B ?

office-sharepoint-server-development
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

1 Answer

Jerryzy avatar image
2 Votes"
Jerryzy answered

Hi @developersp1-9584 ,

Try to upload file into sub folder like this:

 public static void UploadFile(ClientContext context,string uploadFolderUrl, string uploadFilePath)
 {
     var fileCreationInfo = new FileCreationInformation
     {
             Content = System.IO.File.ReadAllBytes(uploadFilePath),
             Overwrite = true,
             Url = Path.GetFileName(uploadFilePath)
     };
     var targetFolder = context.Web.GetFolderByServerRelativeUrl(uploadFolderUrl);
     var uploadFile = targetFolder.Files.Add(fileCreationInfo);
     context.Load(uploadFile);
     context.ExecuteQuery();
 }
    
 using (var ctx = new ClientContext(webUri))
 {
      ctx.Credentials = credentials;
    
      UploadFile(ctx,"LibName/FolderName/Sub Folder Name/Sub Sub Folder Name/Sub Sub Sub Folder Name",filePath);   
 }


If an Answer is helpful, please click "Accept Answer" and upvote it.
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.