I’m currently writing a web service on our SharePoint server to upload documents because one of our clients would like to migrate from a third party document management system to SharePoint.

This client would like to keep the legacy dates like the date of creation and the last modified date. After researching this, I still couldn’t find a way to do this. I noticed there are tools out there are able to do this so it is definitely possible.

So after some more trial and error I finally figured it out. And it wasn’t even that exotic, so I’d like to share how it is done.

When you’ve uploaded the file and checked it in you can change the dates with the following code:

public void UpdateFileDates(string siteCollectionUrl, string site, string file, DateTime created, DateTime modified)
{
    if (siteCollectionUrl == null) throw new ArgumentNullException("siteCollectionUrl");
 
    using (var spSite = new SPSite(siteCollectionUrl))
    using (var web = string.IsNullOrEmpty(site)
                        ? spSite.RootWeb
                        : spSite.OpenWeb(site))
    {
        var spFile = web.GetFile(file);
        if (spFile != null)
        {
            spFile.CheckIn("");
            var item = spFile.Item;
 
            if (item != null)
            {
                item["Created"] = created;
                item["Modified"] = modified;
 
                spFile.CheckOut();
                item.Update();
                //When you do overwritecheckin the version doesn't change.
                spFile.CheckIn("", SPCheckinType.OverwriteCheckIn);
            }
        }
    }
}
Advertisements