1

How can I rename a folder in a list via CSOM (c#).

I tried it with:

var folder = ctx.Web.GetFolderByServerRelativeUrl(folderRelativeUrl);
ctx.Load(folder);
ctx.ExecuteQuery();
var folderItem = folder.ListItemAllFields;
folderItem["Title"] = newTitle;
folderItem["FileLeafRef"] = newTitle;
folderItem.Update();
ctx.Load(folder);
ctx.ExecuteQuery();

and

ListItem folder = getFolderViaCaml();
folder["Name"] = newTitle;
folder["FileLeafRef"] = newTitle;
folder.Update();
ctx.ExecuteQuery();

but I just get the following exception

Invalid data has been used to update the list item. The field you are trying to update may be read only.

3

You need to get the folder item. I don't think you can get the item directly from folder, but you can get it from the list.

Example:

public static void Rename(ClientContext ctx, List list, String oldName, String newName)
{
    const string queryFormat =
        "<View Scope='RecursiveAll'><Query><Where>" +
        "<Eq><FieldRef Name='FileLeafRef' /><Value Type='Text'>{0}</Value></Eq>" +
        "</Where></Query></View>";
    var items = list.GetItems(new CamlQuery
    {
        ViewXml = string.Format(queryFormat, oldName)
    });
    ctx.Load(items);
    ctx.ExecuteQuery();
    items.ToList().ForEach(item =>
    {
        item["FileLeafRef"] = newName;
        item.Update();
    });
    ctx.ExecuteQuery();
}
3

Most probably in the first example the error occurs due to the line shown below:

folderItem.Update();
ctx.Load(folder); //<-loading of folder that has been moved! 
ctx.ExecuteQuery();

Depending on the SharePoint version you could consider the following examples for renaming of folder.

SharePoint 2010

 public static class FolderExtensions
 {
    public static void RenameFolder(this Folder folder,string name)
    {
        var ctx = folder.Context;
        var folderItem = folder.ListItemAllFields;
        folderItem["Title"] = name;
        folderItem["FileLeafRef"] = name;
        folderItem.Update();
        ctx.ExecuteQuery();
    }

}

Usage

 var folder = ctx.Web.GetFolderByServerRelativeUrl(folderRelativeUrl);
 folder.RenameFolder("Archive 2010");

SharePoint 2013

Using Folder.MoveTo method:

var folder = ctx.Web.GetFolderByServerRelativeUrl(sourceFolderRelativeUrl);            
folder.MoveTo(targetFolderRelativeUrl);
ctx.ExecuteQuery();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.