Sunday, July 28, 2013

Copy \ Add Document to Document Set

In this article we can explore the copy document from a document library to document set through code.

Following are the activities involved in copying document:
  • Find the document library
  • Find the document by name
  • Create a byte array from document
  • Find document set and add document to document set
Inside Visual Studio

Create a new console application and name it as DocLibCreation. Make sure you change the target framework to .Net 3.5.

Add the following code into the Program.cs file:

public static void CopyDocument( SPWeb objProjectSite, SPWeb rootSite)
{
objProjectSite.AllowUnsafeUpdates = true;
SPList objList = rootSite.Lists.TryGetList("Source Document Library");
SPFile objFile = null;
Foreach (SPListItem itm in objList.Items)
{
if (itm.Name == "My Document")
{
objFile = itm.File;
break;
}
}
byte[] sourceFileContent = objFile.OpenBinary();
SPList prjDocsList = objProjectSite.Lists.TryGetList("Destination Document Library");
SPFolder folDocSet = objProjectSite.GetFolder("Destination Document Library" + "/" + "Document Set Name");
folDocSet.Files.Add("Document Name" , sourceFileContent, true );
FolDocSet.Update();
ObjProjectSite.AllowUnsafeUpdates = false;
}

No comments:

Post a Comment