Sharing the sample code that we can use for checking if a particular folder exists and if not then create it in SharePoint Online. It uses PnP Framework and Azure Ad App only permissions.
Here we have used the PnP Framework Library in our console application.

We will be checking for and creating the folder at the below location.

On a successful run, we can see the folder named “MyFolder” created the document library.


Below is the sample code
static void Main(string[] args)
{
var siteUrl = "https://w72tk.sharepoint.com/sites/MyTeamSite";
var applicationId = "d7eaeeb7-ef0a-474d-9b94-567013576c14";
var password = "xyz";
var domain = "w72tk.onmicrosoft.com";
var certPath = @"C:\SharePointApp\MyTestCertificate.pfx";
var authManager = new AuthenticationManager(applicationId, certPath, password, domain);
var foldertoCheck = "MyFolder";
using (var clientContext = authManager.GetContext(siteUrl))
{
var currentWeb = clientContext.Web;
var folderExists = currentWeb.DoesFolderExists(foldertoCheck);
if (!folderExists)
{
var list = clientContext.Web.Lists.GetByTitle("Documents");
list.RootFolder.Folders.Add(foldertoCheck);
clientContext.ExecuteQuery();
}
}
}
Refer for more details – https://nishantrana.me/2024/07/30/calling-sharepoint-online-api-using-azure-ad-app-only-permissions-using-certificate-auth/
Hope it helps..



















