From C# to SharePoint – File Upload using CSOM with SubFolders structure

In this article, I will go again through an improved version of how to upload from a C# app (Console, Web Api, Webform …etc.) to a SharePoint Online document library.
In this post, we will have sub folders, as I got this request to upload files under sub folders (customers folder).
The code is straightforward, but before looking at the code, we need to add the following nuggets to the project

It won’t harm to say, that you need to create the document library where the files need to be added , and make sure that the permissions are set properly.
The Code
In my scenario, I have created a console App just for the purpose of this article
static void Main(string[] args) { string SiteUrl = "https://You.sharepoint.com/sites/Upload"; string DocumentLibrary = "UploadLibrary"; string FileName = @"C:\testupload.pdf"; string CustomerFolder = "1564_dsfgsst"; string UserName = "samir.daoudi@******.co.uk"; string Password = "*****"; UploadFileToSharePoint(SiteUrl, DocumentLibrary, CustomerFolder, FileName, UserName, Password); }
I have deliberately added all the parametres in variable, just for those who might to read these from another place, or to make it simple to replace them.
The Upload method
private static void UploadFileToSharePoint(string SiteUrl, string DocLibrary, string ClientSubFolder, string FileName, string Login, string Password) { try { #region ConnectToSharePoint var securePassword = new SecureString(); foreach (char c in Password) { securePassword.AppendChar(c); } var onlineCredentials = new SP.SharePointOnlineCredentials(Login, securePassword); #endregion #region Insert the data using (SP.ClientContext CContext = new SP.ClientContext(SiteUrl)) { CContext.Credentials = onlineCredentials; SP.Web web = CContext.Web; SP.FileCreationInformation newFile = new SP.FileCreationInformation(); byte[] FileContent = System.IO.File.ReadAllBytes(FileName); newFile.ContentStream = new MemoryStream(FileContent); newFile.Url = Path.GetFileName(FileName); SP.List DocumentLibrary = web.Lists.GetByTitle(DocLibrary); //SP.Folder folder = DocumentLibrary.RootFolder.Folders.GetByUrl(ClientSubFolder); SP.Folder Clientfolder = DocumentLibrary.RootFolder.Folders.Add(ClientSubFolder); Clientfolder.Update(); SP.File uploadFile = Clientfolder.Files.Add(newFile); CContext.Load(DocumentLibrary); CContext.Load(uploadFile); CContext.ExecuteQuery(); Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine("The File has been uploaded"+Environment.NewLine+"FileUrl -->"+SiteUrl+"/"+DocLibrary+"/"+ClientSubFolder+"/" +Path.GetFileName(FileName)); } #endregion } catch (Exception exp) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine(exp.Message + Environment.NewLine + exp.StackTrace); } finally { Console.ReadLine(); } }