Home » C# scripts » Scripts to add file in sharepoint folder

Scripts to add file in sharepoint folder

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint.Client;
using System.Collections.Concurrent;
using System.Net;
using System.Net.Http;
using Newtonsoft.Json;
using System.IO;

static void Main(string[] args)
{
  AddFilesToSPFolder("https://abccompany.sharepoint.com/sites/dev/","test@test.com","tester");
}
public static void AddFilesToSPFolder(string sharepointURL, string uName, string pWord)
{
 try
 {
  OfficeDevPnP.Core.AuthenticationManager aM = new OfficeDevPnP.Core.AuthenticationManager();
  using (var abc = aM.GetSharePointOnlineAuthenticatedContextTenant(sharepointURL,uName,pWord))
        {
         Web wb = abc.Web;
         abc.Load(wb);
         abc.Load(wb.Lists);
         abc.ExecuteQueryRetry();
         List mylist = wb.Lists.GetByTitle("Documents");
         abc.Load(mylist);
         abc.ExecuteQueryRetry();
         Folder fdr = null;
         Folder subfolders =null;
         subfolders = mylist.RootFolder.ResolveSubFolder("Folder1");
         if (!subfolders.FolderExists("Folder2"))
            {
             fdr = subfolders.EnsureFolder("Folder2");
            }
         else
            {
            fdr = subfolders.Folders.Where(a => a.Name.Contains("Folder2")).FirstOrDefault();
            }
         Folder fdrToUpload = wb.GetFolderByServerRelativeUrl(fdr.ServerRelativeUrl);
         fdrToUpload.UploadFile("testexcel.xlsx", "C:\\MyFile\\testexcel.xlsx", true);
         fdrToUpload.Update();
         abc.Load(fdr);
         abc.ExecuteQueryRetry();
         fdrToUpload.EnsureProperty(b => b.ServerRelativeUrl);
         var serverRelativeUrl = fdrToUpload.ServerRelativeUrl.TrimEnd('/') + '/' + "testexcel.xlsx";
        }
  }
  catch (Exception ex)
  {
   Console.WriteLine(ex.Message);
   Console.ReadLine();
  }
}

 


Leave a comment

Your email address will not be published. Required fields are marked *