Upload File to SharePoint Office 365 Programmatically using C# CSOM - PNP


Sathish Nadarajan
SharePoint MVP
Published On :   23 Sep 2018
Visit Count
Today :  8    Total :   824



In the earlier article, we saw how to upload the files using the httpclient and the RestAPI which involves a lot of coding. But in PNP (Patterns and practices), it is made very simple. The below code is very straight forward. The only restriction here is, the size cannot be more than 250 MB approx.. if we want to upload a bigger size files, then we have to discuss with the customer and find an alternate way only.

 namespace Office365.Console
 {
     using Microsoft.SharePoint.Client;
     using Newtonsoft.Json;
     using System;
     using System.Collections.Concurrent;
     using System.IO;
     using System.Net;
     using System.Net.Http;
 
     class Program
     {
         private static ConcurrentDictionary<Uri, RESTFormDigest> FormDigests { get; set; }
 
         static void Main(string[] args)
         {
             Uploadfiles();
             System.Console.WriteLine("Completed");
             System.Console.ReadLine();
         }
 
         static string siteUrl = "https://sppalsmvp.sharepoint.com/sites/DeveloperSite/";
         static string userName = "sathish@********.com";
         static string password = "**********";
 
         public async static void Uploadfiles()
         {
             try
             {
                 OfficeDevPnP.Core.AuthenticationManager authMgr = new OfficeDevPnP.Core.AuthenticationManager();
 
                 using (var ctx = authMgr.GetSharePointOnlineAuthenticatedContextTenant(siteUrl, userName, password))
                 {
                     Web web = ctx.Web;
                     ctx.Load(web);
                     ctx.Load(web.Lists);
                     ctx.ExecuteQueryRetry();
                     List list = web.Lists.GetByTitle("D1");
                     ctx.Load(list);
                     ctx.ExecuteQueryRetry();
                     Folder folder = list.RootFolder.EnsureFolder("Folder1");
                     ctx.Load(folder);
                     ctx.ExecuteQueryRetry();
 
                     Folder folderToUpload = web.GetFolderByServerRelativeUrl(folder.ServerRelativeUrl);
                     folderToUpload.UploadFile("LargeFile.txt", "D:\\LargeFile.txt", true);
                     folderToUpload.Update();
                     ctx.Load(folder);
                     ctx.ExecuteQueryRetry();
                     folderToUpload.EnsureProperty(f => f.ServerRelativeUrl);
                     var serverRelativeUrl = folderToUpload.ServerRelativeUrl.TrimEnd('/') + '/' + "LargeFile.txt";
 
 
 
                 }
             }
             catch (Exception ex) {
                 System.Console.WriteLine("Exception occurred : " + ex.Message);
                 System.Console.ReadLine();
             }
         }
 
 
         
     }
 }
 


Happy Coding,

Sathish Nadarajan.

Categories