Code to upload multiple attachments to SharePoint Folder using Client Object Model


public static void UploadDocument(
string siteURL,
string documentListName,
string documentListURL,
string documentName,
byte[] documentStream,
string folderName,
string invoiceId)
{
using (var clientContext = new ClientContext(siteURL))
{
// Get Document List
var documentsList = clientContext.Web.Lists.GetByTitle(documentListName);

// check if folder already exists else create folder

if (!FolderExists(clientContext.Web, documentListName, folderName))
{
var info = new ListItemCreationInformation();
info.UnderlyingObjectType = FileSystemObjectType.Folder;
info.LeafName = folderName.Trim();
var newItem = documentsList.AddItem(info);
newItem["Title"] = folderName;
newItem.Update();
clientContext.ExecuteQuery();
}

var fileCreationInformation = new FileCreationInformation();

// Assign to content byte[] i.e. documentStream
fileCreationInformation.Content = documentStream;

// Allow owerwrite of document
fileCreationInformation.Overwrite = true;

// Upload URL
fileCreationInformation.Url = siteURL + documentListURL + folderName + "/" + documentName;
var uploadFile = documentsList.RootFolder.Files.Add(fileCreationInformation);

// Update the metadata for a field having name "DocType"
uploadFile.ListItemAllFields["Invoice_x0020_Id"] = invoiceId;

uploadFile.ListItemAllFields.Update();
clientContext.ExecuteQuery();
}
}


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);
}


Author: Nishant Rana

I love working in and sharing everything about Microsoft.NET technology !

Share your thoughts

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s