CreatedBy and LastModifiedBy

SharePoint’s PublishingPage object has these two read-only properties. When you migrate content from an existing system to SharePoint you will definetly need to update these two.

This can be easily done for all fields except the LastModifiedBy with the Publishing infrastructure once you know how. It seems quite straight forward, in the end, but it took some time to figure it out. See approach one below.

If that is not enough you can disable versioning, make changes and enable versioning again. See approach two.

Approach 1. After you have created, updated, checked-in and published your migrated page, do the following:

SPFile pageFile = page.ListItem.File;
SPFieldUserValue user = …;
DateTime date = …;
pageFile.Item["Created By"] = user;
pageFile.Item["Modified"] = date;
pageFile.Item.Update();
pageFile.Publish("…");

To update the user you need to use the ‘User’ field type for the ‘Created By’ column. This is the SPFieldUserValue. The ‘Modified’ column take a DateTime object.

How to you retrieve a user from a field:

SPFieldUserValue createdByUser =
  new SPFieldUserValue(
  page.PublishingWeb.Web,
  file.Item["Created By"] as
string
);

How to get the SPUser object:

SPUser createdBySPUser = createdByUser.User;
// Or:
SPUser createdBySPUser = page.CreatedBy;

How to assign an SPUser to a User field:

SPUser user =
  page.PublishingWeb.Web.AllUsers 
  [@"DOMAIN\Bernd"];
  // TBD.

Approach 2. Disable versioning, make your changes, check-in, set modified and created fielsd, update and enable versioning again.

Leave a Reply

Your email address will not be published. Required fields are marked *