Wednesday, March 27, 2013

Change Created/Modified info on a file in a Document Library in SharePoint

This solution works for SharePoint Online (O365). It uses the Claims based authentication for SharePoint Online, but using a standard ClientContext for SharePoint 2010+ should work great also. For the Claims based authentication I am using this library, but you should be able to use this library. If you want to better understand Claims based authentication required for SharePoint Online (O365), then I highly recommend reading this series of articles.The document library you are working on does need to have versioning disabled I believe. If your document library requires versioning, then disable it, then run this code, then enable it again. Please verify that no version history is lost on a copy of your data before doing that though, since I have not tested that.

public static void ChangeCreatedModifiedInfo(string webUrl, string serverRelativeUrlOfFileToChange, DateTime? createdDate, DateTime? modifiedDate, Dictionary<string, object> keyValues)
        {
            using (ClientContext clientContext = ClaimClientContext.GetAuthenticatedContext(webUrl))
            {
                // FYI server relative path is: "/support/CSS/Reports/output.xlsx"
                var uploadedFile = clientContext.Web.GetFileByServerRelativeUrl(serverRelativeUrlOfFileToChange);

                // if not checked out then check it out
                if (uploadedFile.CheckedOutByUser == null)
                {
                    uploadedFile.CheckOut();
                }

                ListItem listItem = uploadedFile.ListItemAllFields;

                clientContext.Load(uploadedFile.ListItemAllFields);
                clientContext.ExecuteQuery();

                // set created and modified date if they are specified
                if (createdDate.HasValue)
                {
                    listItem["Created"] = createdDate.Value.ToString(); // i.e. "6/5/2012 10:19"
                }

                if (modifiedDate.HasValue)
                {
                    listItem["Modified"] = modifiedDate.Value.ToString(); // i.e. "6/5/2012 10:19"
                }

                // set properties based on values passed in
                if (keyValues != null)
                {
                    foreach (var keyValue in keyValues)
                    {
                        listItem[keyValue.Key] = keyValue.Value;
                    }
                }

                listItem.Update();

                uploadedFile.CheckIn(string.Empty, CheckinType.OverwriteCheckIn);

                clientContext.ExecuteQuery();
            }

        }

Not to bad once you have the solution.

No comments: