How to Overwrite SharePoint's Modified Date after Doing a SaveBinaryDirect?

1.3k Views Asked by At

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();
    }
2

There are 2 best solutions below

4
On BEST ANSWER

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();
0
On

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();