Partilhar via


Setting Modified by, Editor and other fields when versioning and content approval is enabled

Most of you are probably aware that setting fields like Modified, Editor, Created and Author require some special attention:

    1: using (SPSite site = new SPSite("https://sp2010"))
    2: using (SPWeb web = site.OpenWeb())
    3: {
    4:     SPFile f = web.GetFile("/Pages/default.aspx");
    5:  
    6:     f.Item["Modified"] = DateTime.Now.AddDays(-2);
    7:     f.Item["Editor"] = "-1;#SHAREPOINT\\SYSTEM";
    8:     f.Item.UpdateOverwriteVersion();
    9: }

So far so good. What happens when content versioning is enabled? calling UpdateOverwriteVersion() results in a new minor version and the approval state going to Pending. The best I could figure out is the following:

    1: using (SPSite site = new SPSite("https://sp2010"))
    2: using (SPWeb web = site.OpenWeb())
    3: {
    4:     SPFile f = web.GetFile("/Pages/default.aspx");
    5:  
    6:     f.Item["Modified"] = DateTime.Now.AddDays(-2);
    7:     f.Item["Editor"] = "-1;#SHAREPOINT\\SYSTEM";
    8:     f.Item.UpdateOverwriteVersion();
    9:  
   10:     f = web.GetFile("/Pages/default.aspx");
   11:  
   12:     f.Item.ModerationInformation.Status = SPModerationStatusType.Approved;
   13:     f.Item.Update();
   14: }

Using this method you can set all fields but the Modified date, which will be set to the time of the approval.