Archive for February, 2012

Programmatically create folder in SharePoint Document library with client object model

SharePoint 2010 has very strong client object library, with the help of client object model we can almost interact with all document related functionality from our application and can interact with SharePoint 2010.

Below is some code snippet for creating new folder in the SharePoint Document Library.

public bool CreateSPFolder(string libname, string correspondance)

{

bool bolReturn = false;

ClientContext ctx = this.GetSPClientContext();

Web web = ctx.Web;

 

List documentLib = ctx.Web.Lists.GetByTitle(libname);

 

string targetFolderUrl = libname + “/” + correspondance;

Folder folder = web.GetFolderByServerRelativeUrl(targetFolderUrl);

ctx.Load(folder);

bool exists = false;

 

try

{

ctx.ExecuteQuery();

exists = true;

}

catch (Exception ex)

{

bolReturn = false;

}

 

 

if (!exists)

{

ContentTypeCollection listContentTypes = documentLib.ContentTypes;

ctx.Load(listContentTypes, types => types.Include

(type => type.Id, type => type.Name,

type => type.Parent));

 

var result = ctx.LoadQuery(listContentTypes.Where

(c => c.Name == “Folder”));

 

ctx.ExecuteQuery();

 

ContentType folderContentType = result.FirstOrDefault();

 

ListItemCreationInformation newItemInfo = new ListItemCreationInformation();

newItemInfo.UnderlyingObjectType = FileSystemObjectType.Folder;

newItemInfo.LeafName = correspondance;

ListItem newListItem = documentLib.AddItem(newItemInfo);

 

newListItem["ContentTypeId"] = folderContentType.Id.ToString();

newListItem["Title"] = correspondance;

newListItem.Update();

 

ctx.Load(documentLib);

ctx.ExecuteQuery();

bolReturn = true;

}

return bolReturn;

}

February 22, 2012 at 11:28 am Leave a comment


Archives

Categories

 

February 2012
M T W T F S S
« Jan   May »
 12345
6789101112
13141516171819
20212223242526
272829  

Blog Stats

  • 1,999

Follow

Get every new post delivered to your Inbox.