0

I'm trying to upload a file to SharePoint Online and I got this sample code:

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

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

Which works perfectly fine, so everything around it works. But apparently this snippet

var uploadFile = list
            .RootFolder
            .Folders
            .GetByPath(ResourcePath.FromDecodedUrl("A/B"))
            .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 "B"?

Jason Aller
  • 3,541
  • 28
  • 38
  • 38
realemx
  • 11
  • 4

1 Answers1

1

Try to upload file 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);   
}

Please check out another similiar thread here:

Alternative Save/OpenBinaryDirect methods for CSOM for SharePoint Online

Jerry
  • 3,480
  • 1
  • 10
  • 12
  • I should have mentioned that we're using .NET core and .SaveBinaryDirect() isn't available. But we scrapped the Plan already as it took too much time. – realemx Oct 09 '20 at 10:04
  • @realemx, for .NET Core solution, I have updated the code in my answer, please check – Jerry Oct 10 '20 at 13:17