Tuesday, September 1, 2009

How to update a SharePoint item while retaining the modified by and date information

In my current project I need to move documents from one document library to another with version history and last modified infomation etc. This works great using SPImport and SPExport.

When the document is moved to the new location, I have a further process of modifiying the values of one of the fields. I needed to do this without modifying the Modified or Modified By fields.

Here is how I did it:

foreach (SPListItem listItem in list.Items)
 {
     var modifiedBy = listItem[SPBuiltInFieldId.Modified_x0020_By];
     var modifiedDate = listItem[SPBuiltInFieldId.Modified];
 
     listItem[_documentTypeFieldName] = GetDocumentType();
     listItem[SPBuiltInFieldId.Modified_x0020_By] = modifiedBy;
     listItem[SPBuiltInFieldId.Modified] = modifiedDate;
     listItem.Update();
 }

BTW. Using Update() creates a new version here. You can not create a new version by using UpdateOverwriteVersion().