How to use PnP.Core SDK to Upload Files with Metadata in SharePoint Online

Introduction

Hi friends, in this post we will see how we can use PnP.Core SDK to upload files including large files in SharePoint Online. In my previous post How to use PnP.Core SDK to secure communication with SharePoint Online, I have shown you the step-by-step approach to the initial setup and configuration. From this post and for future posts, I will be using the same code repo and will add additional methods based on the post.

Why there is a need to upload files?

There are many scenarios that requires the files to be uploaded to SharePoint Online. One of the best scenario is to upload reports and other documents generated by the internal system can be automatically uploaded to SharePoint Online using PnP.Core SDK.

Focus on the Code

Note: I will use the same repo from the previous article so the configuration and other settings we made on the Azure Portal remain the same. The sample code below will upload the files to the default Documents library and update some metadata information.

var filePath = @"C:\Users\sudha\Downloads\CamScanner 12-02-2024 09.34.pdf";
var addedFile = await ctx.Web.Lists.GetByTitle("Documents").RootFolder.Files.AddAsync(System.IO.Path.GetFileName(filePath), System.IO.File.OpenRead(filePath), true);
await addedFile.ListItemAllFields.LoadAsync();
addedFile.ListItemAllFields["IsProcessed"] = true;
addedFile.ListItemAllFields["_ExtendedDescription"] = "This file is uploaded via PnP.Core SDK.";
await addedFile.ListItemAllFields.UpdateAsync();
Console.WriteLine("File uploaded successfully!");

The above code will upload the specific file directly to the Documents folder and update the fields IsProcessed & Description field. The AddAsync method is very powerful method, the same method can be used to upload huge file. The method in PnP.Core automatically breaks the file in to chunks (10 MB) and then upload to the configured location in SharePoint Online.

The below screenshot shows the info when tried to upload a huge file. So the SDK automatically calls the continueupload endpoint to continue the upload.

Conclussion

I hope you had learned something new on PnP.Core SDK. In my future blog post, I am planning to cover the methods related to user profile property update and how to use PnP.Core SDK in Azure Function.

I welcome your suggestions and feedback which will help me in contributing the information that help others to complete their tasks or achieve the business process.

https://github.com/sudharsank/PnPCoreDemo

Leave a comment