Sharepoint 2010: How to Upload a Folder and Containing Files in a Document Library Using Client Object Model
This article is for people who need a tool to upload documents from a local machine to SharePoint document library using client object model in SPS 2010. The solution uses the managed code model to do it.
This tool takes three inputs:
- The URL of the SharePoint site where the library is located.
- The name of the document library.
- Path of the folder in your local machine.
If the folder does not exist, it will create a new folder and if the files already exist, it will overwrite them.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using Microsoft.SharePoint.Client;
namespace TestClientManagedCode
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("This tool will copy the entire folder from your local machine to the sharepoint document library");
Console.WriteLine("Please enter the url of the site");
String siteUrl = Console.ReadLine();
Console.WriteLine("Please enter the name of the document library");
String dLibraryName = Console.ReadLine();
Console.WriteLine("Please enter the full path of the folder containing the files without the filname");
String folderPath = Console.ReadLine();
try
{
using (ClientContext ctx = new ClientContext(siteUrl))
{
Web web = ctx.Web;
ctx.Load(web);
ctx.ExecuteQuery();
List dUplaod = web.Lists.GetByTitle(dLibraryName);
String[] fileNames = Directory.GetFiles(@folderPath);
bool exists = false;
DirectoryInfo dInfo = new DirectoryInfo(@folderPath);
FolderCollection folders = dUplaod.RootFolder.Folders;
char[] sep = { '\\' };
ctx.Load(folders);
ctx.ExecuteQuery();
foreach (Folder eFolder in folders)
{
if (eFolder.Name.Equals(dInfo.Name))
{
foreach (String fileName in fileNames)
{
String[] names = fileName.Split(sep);
FileCreationInformation fCInfo = new FileCreationInformation();
fCInfo.Content = System.IO.File.ReadAllBytes(fileName);
fCInfo.Url = names[names.Length - 1];
eFolder.Files.Add(fCInfo);
exists = true;
}
}
}
if (!exists)
{
Folder tFolder = folders.Add(siteUrl + "/" + dLibraryName + "/" + dInfo.Name);
foreach (String fileName in fileNames)
{
String[] names = fileName.Split(sep);
FileCreationInformation fCInfo = new FileCreationInformation();
fCInfo.Content = System.IO.File.ReadAllBytes(fileName);
fCInfo.Url = names[names.Length - 1];
tFolder.Files.Add(fCInfo);
}
}
ctx.ExecuteQuery();
Console.WriteLine("The Execution is completed");
Console.ReadLine();
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
Console.ReadLine();
}
}
}
}