Showing posts with label Document Library. Show all posts
Showing posts with label Document Library. Show all posts

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

Sunday, July 7, 2013

CAML Query to get all documents from a Document Library

CAML query to retrieve all documents from all folders in a document library.

SPList lstDocs = SPContext.Current.Web.Lists.TryGetList("myDocLib");
SPQuery query = new SPQuery();
query.Query = @"<Where><BeginsWith><FieldRef Name = 'ContentTypeId' /><Value Type= 'ContentTypeId'>0x0101</Value></BeginsWith></Where>";
query.ViewAttributes = "Scope = 'RecursiveAll'";
SPListItemCollection itmsDocs = lstDocs.GetItems(query);