Move Files of SharePoint Document Library using Object Model
Introduction
In this post we will see how to move files of SharePoint document library to one location to another using object model.We will also see how to keep same file Version, Modified and Modified By values after moving
The post includes
- Generic method to move file to destination
- Keeping the file version, Modified and Modified By without any change.
Move file
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
| string siteUrl = "http://sharepoint-devsite.com/DevSite" ; string fileName = "ProjectPlan.docx" ; string sourceDirectory = "/DevSite/Shared Documents" ; string destinationDirectory = "/DevSite/ProjectDocs/ProjTeam/DevTeam/TechLead" ; using (SPSite currSite = new SPSite(siteUrl)) { using (SPWeb currWeb = currSite.OpenWeb()) { MoveFile(currWeb, destinationDirectory, sourceDirectory, fileName); } } public void MoveFile(SPWeb sourceWeb, string sourceDirectory, string destinationDirectory, string fileName) { SPFile sourcefile = sourceWeb.GetFile(sourceDirectory + "/" + fileName); if (sourcefile.Exists) { object modifiedOn = sourcefile.Item[ "Modified" ]; object modifiedBy = sourcefile.Item[ "Modified By" ]; //true - replace if file exists sourcefile.MoveTo(destinationDirectory + "/" + fileName, true ); SPFile dstFile = sourceWeb.GetFile(destinationDirectory + "/" + fileName); SPListItem dstItem = (SPListItem)dstFile.Item; dstItem.ParentList.Fields[ "Modified" ].ReadOnlyField = false ; dstItem.ParentList.Fields[ "Modified By" ].ReadOnlyField = false ; dstItem[ "Modified" ] = modifiedOn; dstItem[ "Modified By" ] = modifiedBy; //updates the item without creating another version of the item dstItem.UpdateOverwriteVersion(); dstItem.ParentList.Fields[ "Modified" ].ReadOnlyField = true ; dstItem.ParentList.Fields[ "Modified By" ].ReadOnlyField = true ; } } MoveFile is the method which moves the file to destination without changing ‘Modified’ and ‘Modified By’ values. |
No comments:
Post a Comment