A blog about SharePoint, Project Server and other Microsoft technologies.

Wednesday, June 25, 2014

SharePoint 2013 - how to move files and folders with versions programmatically

This is a demonstration how you can copy files, folders and Document Set programmatically.

If you want to move just files (documents) inside same SharePoint site and keep all versions of that file, an example is shown in the methodMoveFileWithVersions.

If you have folders that contain multiple files and you want to move one folder with all files that are contained in that folder and all versions of files, then look at methodMoveFolderWithVersions.

But, if you have Document Set (and files inside) and you want to copy it to a different location and keep all versions of these files, it is not possible. You can copy Document Set with all files inside, but you cannot copy versions of these files, you will get only last versions of documents. This is method CopyDocumentSet.

In first two methods (MoveFileWithVersions and MoveFolderWithVersions) you actually move files and folders to a new location, you do not copy it - file (or folder) is only on the new location, but in the last method (CopyDocumentSet), you just copy Document Set - you get same Document Set on new and old location (but on the new location there is only one version of files).If you want to move Document Set and its files with versions to a new location, you can do that if you recreate same Document Set on the new location and copy each individual file from that Document Set withMoveFileWithVersions method.Here is the code created in simple Console Application:

staticvoid Main(string[] args)

{

using (SPSite site = newSPSite("http://dev/sites/test"))

{

using (SPWeb web = site.OpenWeb())

{

SPList oldLib = web.Lists["sourceDocLib"];

SPList newLib = web.Lists["destinationDocLib"];

// move file with all versions MoveFileWithVersions(oldLib, newLib);

// move folder with its files and their versions MoveFolderWithVersions(web, oldLib, newLib);

// copy Document Set - DOES NOT INCLUDE OLD VERSIONS OF THE FILESCopyDocumentSet(web, oldLib, newLib);