Thursday 9 April 2015

Create Document Set in SharePoint 2010 Sandbox solution programmatically

Today I came across a requirement in which I had to create a Document Set in a Sandbox solution programmatically. As DocumentSet.Create function is not supported in Sandbox solution I had to think for another alternative and worked on a little trick and that worked!!
First I created a  folder and then converted that folder content type to Document Set.

You have to first add/enable the Document Set Content Type to the document library to which you are going to create the document set.

Below is the code snippet:

protected void AddToSharePoint(MemoryStream memStream, string fileName)
        {

            using (SPSite site = new SPSite(SPContext.Current.Web.Url.ToString()))
            {
                using (SPWeb web = site.OpenWeb())
                {

                    //Get the document library object
                    SPList docLib = web.Lists["Documents"];
                    SPContentType docSetName = docLib.ContentTypes["Document Set"];
                    if (docLib != null)
                    {
// Create Folder
                        SPListItem folder = docLib.Folders.Add(docLib.RootFolder.ServerRelativeUrl, SPFileSystemObjectType.Folder, "DocSet_" + DateTime.Now.ToString("yyyyMMddHHmmss"));
// Assign Document Set Content Type
                        folder["ContentTypeId"] = docSetName.Id;
                        folder.Update();
//Add a document to the newly created Document Set
                        SPFile file = folder.Folder.Files.Add(fileName, memStream.ToArray(), true);
                        file.Update();
                    }
                }
            }
        }

No comments:

Post a Comment