Retain Modified Date During SharePoint (online) File Transfers Using ClientContext

981 Views Asked by At

I'm essentially trying to download from SharePoint if it has a newer copy of a file or else push mine if mine is newer. I'm never concerned with merging changes in this application. Newer is simply better as the data is all a raw query from a server. So that said, here is what I am doing to compare which file is newer and upload or download accordingly. The problem is, every upload and every download will make the "modified date" be equal to the exact time I do the transfer. I've found I can get the modified date from SharePoint and overwrite the Windows timestamp, but I'm not sure how to go the other way. I'd also accept if there was a way to retain the value to begin with depending on the impact to my current code. So how can I either retain or modify it?

        using (var ctx = new ClientContext(DataSharepointSite))
        {
            ctx.AuthenticationMode = ClientAuthenticationMode.Default;
            ctx.Credentials = GetSharepointCredentials();

            var file = ctx.Web.GetFileByServerRelativeUrl(sharepointFile);
            var fileData = file.OpenBinaryStream();
            ctx.Load(file);
            ctx.ExecuteQuery();
            using (var sr = new StreamReader(fileData.Value))
            {
                DateTime lastDataUpdate = System.IO.File.GetLastWriteTime(localFile).ToUniversalTime();
                DateTime ShareDate = file.TimeLastModified.ToUniversalTime();

                // If SharePoint has a newer file, download it
                if (ShareDate > lastDataUpdate)
                    using (FileStream fs = new FileStream(localFile, FileMode.Create))
                    {
                        sr.BaseStream.CopyTo(fs);
                    }
                    // Forced to overwrite modified date to match SharePoint
                    System.IO.File.SetLastWriteTime(localFile, ShareDate);
                }
                // else if local copy is newer, push to SharePoint
                else if (ShareDate < lastDataUpdate)
                {
                    using (FileStream fs = new FileStream(localFile, FileMode.Open))
                    {
                        // This, too, is getting a new "modified date" so next compare will re-download
                        Microsoft.SharePoint.Client.File.SaveBinaryDirect(ctx, sharepointFile, fs, true);
                    }
                }
            }
1

There are 1 best solutions below

0
On BEST ANSWER
file.ListItemAllFields["Modified"] = System.IO.File.GetLastWriteTime(localFile);
file.ListItemAllFields.Update();
ctx.ExecuteQuery();