You are right to be concerned. Even the MoveTo method can sometimes trigger updates to the Modified and Modified By fields, depending on the specific SharePoint environment and configuration. Unfortunately, there's no guaranteed, 100% foolproof way to prevent these fields from being updated using CSOM when renaming a folder. SharePoint's internal mechanisms can sometimes override your attempts to preserve metadata.
Given that, here's the most reliable strategy, which involves saving the original values and restoring them after the rename. This is the closest you can get to the desired outcome, but it's still not perfect and has potential drawbacks:
using Microsoft.SharePoint.Client;
using System;
public static void UpdateFolderNamePreserveTimestamps(ClientContext context, string listTitle, string folderName, string newFolderName)
{
List list = context.Web.Lists.GetByTitle(listTitle);
context.Load(list);
Folder folder = context.Web.GetFolderByServerRelativeUrl($"{list.RootFolder.ServerRelativeUrl}/{folderName}");
context.Load(folder, f => f.ListItemAllFields); // Load the ListItemAllFields
context.ExecuteQuery();
if (folder != null && folder.Exists)
{
// 1. Store the original Modified and Modified By values
ListItem item = folder.ListItemAllFields;
context.Load(item);
context.ExecuteQuery();
DateTime originalModified = (DateTime)item["Modified"];
FieldUserValue originalModifiedBy = (FieldUserValue)item["Editor"]; // Or "Modified By" depending on locale
context.Load(originalModifiedBy); //Load the user
context.ExecuteQuery();
// 2. Rename the folder
string oldUrl = folder.ServerRelativeUrl;
folder.MoveTo(folder.ServerRelativeUrl.Replace(folderName, newFolderName), MoveOperations.Overwrite);
context.ExecuteQuery();
// Get the item after the rename.
folder = context.Web.GetFolderByServerRelativeUrl($"{list.RootFolder.ServerRelativeUrl}/{newFolderName}");
context.Load(folder, f => f.ListItemAllFields); // Load the ListItemAllFields
context.ExecuteQuery();
item = folder.ListItemAllFields;
context.Load(item);
context.ExecuteQuery();
// 3. Restore the original Modified and Modified By values
item["Modified"] = originalModified;
item["Editor"] = originalModifiedBy; // Or "Modified By" depending on locale
item["SystemUpdate"] = true; // Bypass some checks, use with caution!
item.Update();
context.ExecuteQuery();
Console.WriteLine("Folder name updated, attempting to preserve timestamps.");
}
else
{
Console.WriteLine("Folder not found.");
}
}
Key Changes and Explanations:
- Store Original Values:
- Before renaming, the code retrieves the associated with the folder.