SharePoint Search and changing the Created and LastModified fields

If you want to change the LastModified and Created fields of a list item or a document you can use this code to do that:


SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite site = new SPSite("site + web url"))
{
using (SPWeb web = site.OpenWeb())
{
web.AllowUnsafeUpdates = true;
SPListItem listItem = web.GetListItem(this.tbItemURL.Text);

if (this.cCreatedDate.SelectedDate != new DateTime())
listItem[SPBuiltInFieldId.Created] = this.cCreatedDate.SelectedDate;
else
listItem[SPBuiltInFieldId.Created] = listItem[SPBuiltInFieldId.Created];

if (this.cModifiedDate.SelectedDate != new DateTime())
listItem[SPBuiltInFieldId.Modified] = this.cModifiedDate.SelectedDate;
else
listItem[SPBuiltInFieldId.Modified] = listItem[SPBuiltInFieldId.Modified];

listItem.UpdateOverwriteVersion();
if (listItem.ParentList.EnableMinorVersions)
{
listItem.File.Publish("SPFileUpload");
}
if (listItem.ModerationInformation != null)
{
listItem.File.Approve("SPFileUpload");
}




web.AllowUnsafeUpdates = false;
}
}
});

The reason why the above is done is because if you simply change the date values and use the UpdateOverwireVersion() it will not be enough. The search will not be able to index right values EVEN if you check the UI or use PowerShell or SharePoint Manager etc. All of those show that the value is OK but actually is not. The manually inserted dates will not show up in search unless the item or document is published and approved. So no matter that SP says remember this :).

another thing is that this code above does not allow to set a LastModified IF you have publishing/versioning enabled. After calling the UpdateOverwriteVersion function the item or document will be checked out and remains in that state until something is done. Once you do that you are back to where you started the modified date is changed automatically by SP.

Do not have a solution yet. Maybe you have?

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s