Thursday, December 17, 2015

Bulk Upload Files to SharePoint remotely using CSOM in SharePoint Online

Bulk Upload Files to SharePoint remotely using CSOM in SharePoint Online
Using PowerShell: https://gallery.technet.microsoft.com/PowerShell-Bulk-Upload-b9e9d600
------------------------------------------------------------------------------------------------
using Microsoft.SharePoint.Client;
using SP = Microsoft.SharePoint.Client;
using System;
using System.IO;
using System.Linq;
using System.Security;
namespace WebApplication1
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        const string webUrl = "https://sreekanth2.sharepoint.com/";
        const string USER = "sreekanth@sreekanth2.onmicrosoft.com";
        const string PWD = "Password";
        const string parent_dir = @"D:\ToUploadFilesFolder";
        const string listTitle = "MyDocuments"; // Library Display Name and Url should be same.
        public string parent_folderName = "";
        public string sub_folderName = "";
        public string fileName = "";
        public string file_relativeUrl = "";
        protected void Page_Load(object sender, EventArgs e)
        {
            using (ClientContext clientContext = new ClientContext(webUrl))
            {
                SecureString passWord = new SecureString();
                foreach (char c in PWD.ToCharArray())
                {
                    passWord.AppendChar(c);
                }
                clientContext.Credentials = new SharePointOnlineCredentials(USER, passWord);
                var arrayfolderName = parent_dir.Split(new char[] { '\\' }, StringSplitOptions.RemoveEmptyEntries);
                parent_folderName = arrayfolderName[arrayfolderName.Length - 1];
                if (!FolderExists(clientContext.Web, listTitle, parent_folderName))
                {
                    CreateFolder(clientContext.Web, listTitle, parent_folderName);
                }
                DirSearch(clientContext, parent_dir);
            }
        }
        private void DirSearch(ClientContext clientContext, string dir)
        {
            try
            {
                foreach (string f in Directory.GetFiles(dir))
                {
                    fileName = f.Split(new string[] { dir }, StringSplitOptions.RemoveEmptyEntries)[0].Replace("\\", "/");
                    file_relativeUrl = parent_folderName + "/" + f.Split(new string[] { parent_dir + "\\" }, StringSplitOptions.RemoveEmptyEntries)[0].Replace("\\", "/");
                    //div1.InnerHtml += "/" + file_relativeUrl + "</br>";
                    using (FileStream fs = new FileStream(dir + "\\" + fileName, FileMode.Open))
                    {
                        SP.File.SaveBinaryDirect(clientContext, "/" + listTitle + "/" + file_relativeUrl, fs, true);
                    }
                }
                foreach (string d in Directory.GetDirectories(dir))
                {
                    sub_folderName = d.Split(new string[] { parent_dir + "\\" }, StringSplitOptions.RemoveEmptyEntries)[0].Replace("\\", "/");
                    //div1.InnerHtml += parent_folderName + "/" + sub_folderName + "</br>";
                    if (!FolderExists(clientContext.Web, listTitle, parent_folderName + "/" + sub_folderName))
                    {
                        CreateFolder(clientContext.Web, listTitle, parent_folderName + "/" + sub_folderName);
                    }
                    DirSearch(clientContext, d);
                }
            }
            catch (System.Exception ex)
            {
                div1.InnerHtml += ex.Message + " " + ex.StackTrace;
            }
        }
        public static bool FolderExists(Web web, string listTitle, string folderUrl)
        {
            var list = web.Lists.GetByTitle(listTitle);
            var folders = list.GetItems(CamlQuery.CreateAllFoldersQuery());
            web.Context.Load(list.RootFolder);
            web.Context.Load(folders);
            web.Context.ExecuteQuery();
            var folderRelativeUrl = string.Format("/{0}/{1}", list.RootFolder.Name, folderUrl);
            return Enumerable.Any(folders, folderItem => (string)folderItem["FileRef"] == folderRelativeUrl);
        }
        private static void CreateFolder(Web web, string listTitle, string folderName)
        {
            var list = web.Lists.GetByTitle(listTitle);
            var folderCreateInfo = new ListItemCreationInformation
            {
                UnderlyingObjectType = FileSystemObjectType.Folder,
                LeafName = folderName
            };
            var folderItem = list.AddItem(folderCreateInfo);
            folderItem.Update();
            web.Context.ExecuteQuery();
        }
    }
}
------------------------------------------------------------------------------------------------

No comments:

Post a Comment