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("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 (9)

  1. Ali says:

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

  2. motnis says:

    this doesnt work when you have multiple language packs installed…

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


  4. sowmyancs says:

    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.

  5. 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";

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

  7. Jeff says:

    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?

  8. Carl says:

    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.

Skip to main content