Copy/Upload files and use the old Last Modified or Created date-time of documents


You may read in the SDK about the Add method:

SPFileCollection.Add Method (Microsoft.SharePoint) 
http://msdn2.microsoft.com/en-us/library/microsoft.sharepoint.spfilecollection.add.aspx

You tried the sample http://msdn2.microsoft.com/en-us/library/ms439259.aspx

System.DateTime created = srcFile.TimeCreated;
System.DateTime modified = srcFile.TimeLastModified;
destFiles.Add(destURL, binFile, userAuthor, userModified, created, modified);

The community content told you that this did not work and the solution for a complete copy action could looks like:

Put this into a method:

// Initialize my objects

SPSite site = new SPSite(http://ServerName/SiteDirectory/SiteName);
SPWeb ThisSite = site.AllWebs["/sitedirectory/SiteName"];
SPFolder srcFolder = ThisSite.Folders["SourceFLD"];
SPFileCollection destFiles = ThisSite.Folders["DestFLD"].Files;

// Here we copy each file from the source to the destination folder (doclib)

foreach (SPFile srcFile in srcFolder.Files)

{
   string destURL = destFiles.Folder.Url + "/" + srcFile.Name;
  
byte[] binFile = srcFile.OpenBinary();
  
SPUser userAuthor = srcFile.Author;
   SPUser userModified = srcFile.ModifiedBy;
   System.DateTime created = srcFile.TimeCreated;
   System.DateTime modified = srcFile.TimeLastModified;

   // Return Value
   // A Microsoft.SharePoint.SPFile object that represents the file.
   // We need this here to get the particular list item
   SPFile retValue;
   retValue = destFiles.Add(destURL, binFile, userAuthor, userModified,
              created, modified);
   SPListItem MyListItem = retValue.Item;

   // We can use an own value or the old one
   // MyListItem["Created"] = new DateTime(2007, 4, 4);
   MyListItem["Created"] = srcFile.TimeCreated;

   // We can use an own value or the old one
   // MyListItem["Modified"] = new DateTime(2007, 5, 5);

   MyListItem["Modified"] = srcFile.TimeLastModified;

   // Not needed here but possible
   // MyListItem["Author"] = srcFile.Author;

   // Not needed here but possible
   // MyListItem["Editor"] = srcFile.ModifiedBy;

   MyListItem.UpdateOverwriteVersion();

}


Comments (4)

  1. maruR says:

    Could you please advise a novice how they should go about adding this method?

    I will get a developer to actually do it but I need to get them started and explain the context.

  2. bungle says:

    Well, this does not work either as UpdateOverwriteVersion does UnPublish call that makes docs draft.

  3. bungle says:

    And when you do Publish Moss modifies Last Modified By column :-(.

  4. Good questions because we can have doclibs with versioning and also "Need to CheckOut" before editing. It might be you should check this before and create a workaround appropriate.

Skip to main content