0

I can push a file to SharePoint, but the modified date is always equal to the exact time I uploaded it. How can I overwrite the modified date to be equal to the value of the file? The code below was my failing guess after many searches.

Using "TimeLastModified" seems to error as non-existent while "Modified" seems to not error but the subsequent ExecuteQuery then gives an unknown error.

    using (var ctx = new ClientContext(DataSharepointSite))
    {
        ctx.AuthenticationMode = ClientAuthenticationMode.Default;
        ctx.Credentials = GetCreds();
        using (FileStream fs = new FileStream(localFile, FileMode.Open))
        {
            Microsoft.SharePoint.Client.File.SaveBinaryDirect(ctx, sharepointFile, fs, true);
        }

        //****************
        // Now somehow set Modified Date to local File's Modified Date
        //****************
        var file = ctx.Web.GetFileByServerRelativeUrl(sharepointFile);
        ListItem lstItem = file.ListItemAllFields;
        ctx.Load(lstItem);
        ctx.ExecuteQuery();
        lstItem["TimeLastModified"] = System.IO.File.GetLastWriteTime(localFile).ToUniversalTime();
        lstItem.Update();
        ctx.ExecuteQuery();
    }
CodeMonkey
  • 1,795
  • 3
  • 16
  • 46

2 Answers2

0

I was so close! Looks like the Load and first ExecuteQuery were also not needed. Now I just don't know if it's read as local or UTC...

lstItem["Modified"] = System.IO.File.GetLastWriteTime(localFile).ToUniversalTime().ToString();
CodeMonkey
  • 1,795
  • 3
  • 16
  • 46
0

Try the code snippet to update Modified field:

        var file = ctx.Web.GetFileByServerRelativeUrl(sharepointFile);
        ListItem lstItem = file.ListItemAllFields;
        ctx.Load(lstItem);
        ctx.ExecuteQuery();
        lstItem["Modified"] = System.IO.File.GetLastWriteTime(localFile).ToShortDateString();
        lstItem.Update();
        ctx.ExecuteQuery();
Jerry
  • 3,480
  • 1
  • 10
  • 12
  • It doesn't appear as if the first Load and Execute are necessary. Can you explain them? – CodeMonkey Mar 23 '21 at 11:53
  • ctx.Load(lstItem); ctx.ExecuteQuery(); loading the field values for the file object, then lstItem["Modified"] can access and update. Anyway the code snippet should be working to update Modified field. – Jerry Mar 23 '21 at 13:08
  • I guess the Load and first Execute are only necessary if I want to view the fields. I can set one without first populating it and then have it update. I do wonder if that would ever override anything important though. I didn't see anything overwritten, but it might be a good precaution to populate then change and update. – CodeMonkey Mar 23 '21 at 16:37
  • Yes, it's better to load and execute before updating field :) – Jerry Mar 24 '21 at 12:25