Programmatically rename a file inside a SharePoint document library

Programmatically rename a file inside a SharePoint document library

  • Comments 9

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("http://<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
  • PingBack from http://www.easycoded.com/programmatically-rename-a-file-inside-a-sharepoint-document-library/

  • Can we rename a sharepoint list? programmtically, i know it is possible using the sharepoint designer.

  • this doesnt work when you have multiple language packs installed...

  • motnis, why and how can i see if multiple language packs have been installed.

    thanks

  • 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.

  • 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";

  • ok disregard, i had swapped out the array with the actual file name i was looking for, it's working now.

  • 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?

  • 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.

Page 1 of 1 (9 items)
Leave a Comment
  • Please add 7 and 5 and type the answer here:
  • Post