Search code examples
c#sharepointsharepoint-onlinecsom

How to update File metadata in Sharepoint CSOM?


I know this question has been asked in the past, but I can't seem to find a working solution. I want to update The CreatedDateTime, ModifiedBy and CreatedBy metadata on a file that I uploaded with CSOM. I have this code. It does not crash, but does not update the properties either.

            FileCreationInformation newFile = new FileCreationInformation();
            byte[] FileContent = null;
           
            using (var webClient = new WebClient())
            {
                webClient.Headers.Add("Authorization", authorization);
                FileContent = webClient.DownloadData(file.DowlnloadUrl);
            }

            newFile.ContentStream = new System.IO.MemoryStream(FileContent);
            newFile.Url = System.IO.Path.GetFileName(file.Name);
            Microsoft.SharePoint.Client.File sharepointFile = _spFolder.Files.Add(newFile);
            _context.ExecuteQuery();

            sharepointFile.ListItemAllFields["Modified"] = DateTime.Today.AddDays(-3);
            sharepointFile.ListItemAllFields["Created"] = DateTime.Today.AddDays(-3);
            sharepointFile.ListItemAllFields.Update();
            _context.ExecuteQuery();

The file still appears that it was created/modified a few seconds ago. enter image description here

Any help would be appreciated. PS: if this can be done in one go (one single ExecuteQuery), that would be great.


Solution

  • I ended up finding a code snippet that works. Beware, this works only if the account your are using to generate the context is a Sharepoint Admin (has the SP admin role, and not only a Global Admin role). Being an owner of the site does not suffice either.

    Code can be found here: https://www.c-sharpcorner.com/blogs/update-a-sharepoint-listitem-without-increasing-its-item-file-version-using-sharepoint-client-side-modelcsom