Renaming a Document Item in a SharePoint Document Library

tl;dr: item[SPBuiltInFieldId.FileLeafRef] = "filename";

So I'm back doing nuts and bolts type SharePoint development and last night, I couldn't remember quite how to rename a file in a document library. Sure, you can set item["Title"] to something new, but that doesn't change the file name (right?). Now, there are plenty of articles and Stack Overflow/Stack Exchange questions where people tell you to use the "Name" field to update the file name. Sure, that's cool. And it works. But, and hopefully you know about this already, for any of the built in fields in SharePoint, you should be using members from the SPBuiltInFieldId class whenever you access or update one of those fields.

So, stop writing,

item["Title"] = "A People's History of the United States";

or

item["Author"] = "dev\\hunter";

Instead of those magic strings, you should be using something like

item[SPBuiltInFieldId.Title] = "The Omnivore's Dilemma";

or

item[SPBuiltInFieldId.Author] = "dev\\not.hunter";

Or, even better, on that second one, get yourself an SPUser object like you're supposed to, create an SPFieldUserValue object using the user ID and login name. But that's a post for another day.

Back to how to rename a file in a document library, though. Instead of using item["Name"], please use:

item[SPBuiltInFieldId.FileLeafRef] = "Whatever ole filename you like.awesome";

Yes, "Name" works fine, but get in the habit of using the class you've been given. You'll save yourself some headaches at some point.