Saturday, July 24, 2010

How to update the Created by & Modified by fields in Sharepoint Document library?

Scenario:-


1. While uploading the file into SharePoint Document library we need to re-assign the Created by and Modified by Column values.

2. While migrating document library .

Normally we do these process in system account (run the code block in elevated privilege), In this case the created by and Modified by field values were assigned as "System Account". How to changed to the current logged user name.

Note : There is no SDK method to update Created by and Modified by field information for existing files in a document library.

Solution :-

1. For New Upload :  .Files.Add method has parameter.
2. Update Existing Document :  Create new document and assign the existing metadata & permission, then delete the old one. ( but you will new document unique ID).


Sample Code snippet :

//Get the SPUser object for createdby user
SPUser CreatedBy = oWeb.AllUsers[CreatorLoginID] // SPContext.Current.Web.CurrentUser;

//Get the SPUser object for modifiedby user
SPUser ModifiedBy = oWeb.AllUsers[Modifier]// SPContext.Current.Web.CurrentUser;

//Open the file, read its contents and then close it
FileStream mystream = new FileStream(sFilePath, FileMode.Open);
byte[] contents = new byte[mystream.Length];
mystream.Read(contents, 0, (int)mystream.Length);
mystream.Close();

//Upload the file to library
SPFile file = _oList.RootFolder.Files.Add(sFileName, contents, CreatedBy, ModifiedBy, timeCreated, timeModified);

//Update metadata and also created and last modified datetime again
SPListItem Newitem = file.Item;
Newitem ["Title"] = strItemTitle;
Newitem ["Description"] = strItemDescription;
Newitem ["Created"] = timeCreated;
Newitem ["Modified"] = timeModified;
file.Item.Update();

No comments: