Use below code to upload docs and create any number of nested folders using client object model from local machine
Check if library exists, if not then create library and then upload docs
Create folders and files inside folders :
{
static ClientContext clientContext;
static List list;
static void Main(string[] args)
{
clientContext = new ClientContext("https://sharepointsite");
list = GetListByTitleCS(clientContext, "TargetFolder");
if (list == null)
{
ListCreationInformation lci = new ListCreationInformation();
lci.Title = "TargetFolder";
lci.Description = "TargetFolder";
lci.TemplateType = (Int32)ListTemplateType.DocumentLibrary;
lci.QuickLaunchOption = QuickLaunchOptions.On;
List library = clientContext.Web.Lists.Add(lci);
clientContext.ExecuteQuery();
}
//DataTable dt = new DataTable();
//DataTable dtRecords = new DataTable();
//dtRecords.Columns.Add("Ref");
//dtRecords.Columns.Add("Title");
//dtRecords.Columns.Add("Exception");
try
{
string[] files;
string relativeurl;
// dirs = Directory.GetFiles("C:\\archives Multiple");
string root = @"C:\archives Multiple";
// Get all subdirectories
string[] subdirectoryEntries = Directory.GetDirectories(root);
// Loop through them to see if they have any other subdirectories
foreach (string subdirectory in subdirectoryEntries)
{
ListItemCreationInformation itemCreateInfo = new ListItemCreationInformation();
var foldernames = subdirectory.Split('\\');
var foldername = foldernames[foldernames.Length - 1];
itemCreateInfo.UnderlyingObjectType = FileSystemObjectType.Folder;
itemCreateInfo.LeafName = foldername;
ListItem newItem = list.AddItem(itemCreateInfo);
newItem["Title"] = foldername;
newItem.Update();
clientContext.ExecuteQuery();
LoadSubDirs(subdirectory);
}
files = Directory.GetFiles(root);
foreach (string file in files)
{
try
{
List documentsList = clientContext.Web.Lists.GetByTitle("TargetFolder");
clientContext.Load(documentsList.RootFolder);
clientContext.ExecuteQuery();
if (Path.GetFileName(file) == "Thumbs.db") continue;
var filepathreplace = Path.GetFileName(file);
if (filepathreplace != null)
{
filepathreplace = new Regex("([~!@#$%^&*()]|(?:[.](?![a-z0-9]+$)))", RegexOptions.IgnoreCase).Replace(filepathreplace, "_");
}
using (var fileStream = new FileStream(file, FileMode.Open))
{
relativeurl = documentsList.RootFolder.ServerRelativeUrl + "/" + filepathreplace;
Microsoft.SharePoint.Client.File.SaveBinaryDirect(clientContext, relativeurl, fileStream,
true);
clientContext.ExecuteQuery();
}
}
catch (Exception ex)
{
// libOperations.ErrorLog(ex, file);
}
}
}
catch (Exception ex)
{
//dtRecords.Rows.Add(Convert.ToString(row["Doc Id"]).Trim(), Convert.ToString(row["Subject"]).Trim(), ex.Message);
// libOperations.ErrorLog(ex, Convert.ToString(row["Doc Id"]));
}
}
private static void LoadSubDirs(string dir)
{
string parentfolder = dir.Split(new string[] { "archives Multiple" }, StringSplitOptions.None).Last();
parentfolder = parentfolder.Replace(@"\", "/");
//Console.WriteLine(dir);
var web = clientContext.Web;
string[] subdirectoryEntries = Directory.GetDirectories(dir);
foreach (string subdirectory in subdirectoryEntries)
{
string Fullfilenamepath = subdirectory.Split(new string[] { "archives Multiple" }, StringSplitOptions.None).Last();
//string searchInputs = "and and and and and asp.net and C# and Sqlserver and java and and and and";
var foldernames = subdirectory.Split('\\');
var foldername = foldernames[foldernames.Length - 1];
clientContext.Load(list.RootFolder);
web.Context.ExecuteQuery();
string listrootfolder = list.RootFolder.Name.ToString();
string targetFolderUrl = list.RootFolder.ServerRelativeUrl + parentfolder;
var folder1 = clientContext.Web.GetFolderByServerRelativeUrl(targetFolderUrl);
clientContext.Web.Context.Load(folder1);
clientContext.Load(folder1);
web.Context.ExecuteQuery();
var curFolder = folder1.Folders.Add(foldername);
web.Context.ExecuteQuery();
LoadSubDirs(subdirectory);
}
string[] files;
string[] directories;
string relativeurl;
// int foldercounter = 0;
files = Directory.GetFiles(dir);
foreach (string file in files)
{
//foldercounter++;
try
{
var foldernames = dir.Split('\\');
string Fullfilenamepath = file.Split(new string[] { "archives Multiple" }, StringSplitOptions.None).Last();
Fullfilenamepath = Fullfilenamepath.Replace(@"\", "/");
var foldername = foldernames[foldernames.Length - 1];
List documentsList = clientContext.Web.Lists.GetByTitle("TargetFolder");
clientContext.Load(documentsList.RootFolder);
clientContext.ExecuteQuery();
if (Path.GetFileName(file) == "Thumbs.db") continue;
var filepathreplace = Path.GetFileName(file);
if (filepathreplace != null)
{
filepathreplace = new Regex("([~!@#$%^&*()]|(?:[.](?![a-z0-9]+$)))", RegexOptions.IgnoreCase).Replace(filepathreplace, "_");
}
using (var fileStream = new FileStream(file, FileMode.Open))
{
relativeurl = documentsList.RootFolder.ServerRelativeUrl + "/" + Fullfilenamepath;
//relativeurl = documentsList.RootFolder.ServerRelativeUrl + "/" + dir.Split('C:\\archives Multiple\\') + foldername + "/" + filepathreplace;
Microsoft.SharePoint.Client.File.SaveBinaryDirect(clientContext, relativeurl, fileStream,
true);
clientContext.ExecuteQuery();
}
}
catch (Exception ex)
{
// libOperations.ErrorLog(ex, file);
}
}
}
public static List GetListByTitleCS(ClientContext clientContext, String listTitle)
{
List existingList;
Web web = clientContext.Web;
ListCollection lists = web.Lists;
IEnumerable<List> existingLists = clientContext.LoadQuery(
lists.Where(
list => list.Title == listTitle)
);
clientContext.ExecuteQuery();
existingList = existingLists.FirstOrDefault();
return existingList;
}
// libOperations.Excel_FromDataTable(dtRecords);
}