How do I programmatically rename a Sharepoint directory (SPFolder or SPListItem)?

13k views Asked by At

I have tried this:

SPFolder folder = ...;
folder.Item["Name"] = newName;
folder.Item.Update();

And it behaves mysteriously. If I run it, it throws an exception:

 SPException: Cannot complete this action.

HOWEVER, if I stop it in the debugger after the new Name assignment and before the Update(), and look at the properties of folder.Item, then continue, it works every time. It's not a timing thing, I tried stopping it in the debugger without looking at it in the Locals window, but it threw an exception that time.

This question indicates a similar solution but using SystemUpdate(), does that matter? Programmatically changing name of SPFolder

6

There are 6 answers

1
Tom Vervoort On

You do not need to change the name, but te title. So:

folder.Item[SPBuiltInFieldId.Title] = newName;
folder.Item.Update(); // or SystemUpdate(false)

The difference between Update and SystemUpdate is that Update will change modified / modified by information and if versioning is enabled it will increase the version number. SystemUpdate does not update these.

Also note that I use SPBuiltInFieldId.Title. This is better than using "Title", because "Title" may cause issues in sites that are not in English.

0
hemen.rohani On
folder.Item["Name"] = newName;
folder.ParentWeb.AllowUnsafeUpdates = true;
folder.Item.Update();
folder.ParentWeb.AllowUnsafeUpdates = false;

this fork for me

0
Netsh On

Try to add before the action "folder.ParentWeb.AllowUnsafeUpdates = true" and after it bring back the AllowUnsafeUpdates to it's previous value.

0
Nishant On
 SPFolder attachfolder = documentLibrary.RootFolder.SubFolders[guid];
            //rename guid to new item id
            attachfolder.Properties[SPBuiltInFieldId.Title.tostring()] = itemID;
            attachfolder.Update();
0
Panos Bariamis On

In a Document Library the field Name of an item (folder) has StaticName = FileLeafRef. So what really worked for me is

folder.Item[SPBuiltInFieldId.FileLeafRef] = "The new name";
folder.Item.Update();
0
Vedran On

You can try using the MoveTo method