CSOM - Upload a file to a subdirectory in Sharepoint Online

developer sp1 461 Reputation points
2020-10-15T03:17:30.397+00:00

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 ?

SharePoint Server Development
SharePoint Server Development
SharePoint Server: A family of Microsoft on-premises document management and storage systems.Development: The process of researching, productizing, and refining new or existing technologies.
1,576 questions
0 comments No comments
{count} votes

Accepted answer
  1. Jerryzy 10,566 Reputation points
    2020-10-15T07:56:25.357+00:00

    Hi @developer sp1 ,

    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.

    2 people found this answer helpful.
    0 comments No comments

0 additional answers

Sort by: Most helpful