Programmatically rename a file inside a SharePoint document library
We can’t rename a file using file property SPFile.Name, it will say "Property or indexer 'Microsoft.SharePoint.SPFile.Name' cannot be assigned to -- it is read only.", then how we can rename a file ?
Yes, the “name” and “display name” are read-only fields, so you will get an error at the time of compilation. But you can rename a file in a document library by the following way.
1: SPSite oSite = new SPSite("https://<sitename>/");
2: SPWeb oWeb = oSite.OpenWeb();
3: SPList oList = oWeb.Lists["Shared Documents"];
4: SPListItem oListItem = oList.Items[0];
5: oListItem.File.CheckOut();
6: oListItem["Name"] = "xyz";
7: oListItem.Update();
8: oListItem.File.CheckIn("file name has been changed");
9: oWeb.Dispose();
Comments
Anonymous
October 01, 2008
PingBack from http://www.easycoded.com/programmatically-rename-a-file-inside-a-sharepoint-document-library/Anonymous
March 09, 2009
Can we rename a sharepoint list? programmtically, i know it is possible using the sharepoint designer.Anonymous
December 28, 2009
this doesnt work when you have multiple language packs installed...Anonymous
February 15, 2011
motnis, why and how can i see if multiple language packs have been installed. thanksAnonymous
February 15, 2011
You can see the language packs installed for SharePoint - Control Panel -> Add or Remove Programmes. I think you can rename the list once you open SPWeb Instance with the exact Language ID. I haven't tested it though.Anonymous
February 15, 2011
are the language packs specific to the machine or the SPdatabase running the code above i get an argument exception was unhandled saying value does not fall with the expected range the file is called test.doc in the document library oListItem["test"] = "jeffchange";Anonymous
February 15, 2011
ok disregard, i had swapped out the array with the actual file name i was looking for, it's working now.Anonymous
February 17, 2011
ok so some of the files are checked out by users, i tried to check the files in before i looped thru them and checked them out for renaming - but it breaks saying the file is checked out or locked for editing by the user. is there another way to rename files that are checked out?Anonymous
March 02, 2011
You could check the file in, change the name, then check the file back out to the user. You might already have the user token to check it back out as the user.