Goal: Using an event receiver, change the name of a document in a document library during the ItemUpdated
event when a user edits a docuement with other meta data fields.
I'm using an event receiver ItemUpdated
to change the Name field of a document in a Document Library. When a user edits the document from the document library, there is one field "File Type" that the user has the option to change. The problem I'm running into is when the user changes the name field and changes the File Type in a single save. I get an SPException
when when the listItem.SystemUpdate(true) runs saying "Cannot open "DocumentLibraryName/ Old File Name": no such file or folder." Note that the error is referring to the old file name.
Example of this would be: List Item with the Name of "File1", after a user has changed it to "File2" and changed the File Type field the error will display "Cannot open "DocumentLibraryName/File1": no such file or folder."
This error doesn't happen when I change the List Item Name by itself or when I change the File Type field by itself.
Here is the code I'm working with:
public override void ItemUpdated(SPItemEventProperties properties)
{
SPListItem listItem = properties.ListItem;
string beforeFileName = listItem["Name"].ToString();
string afterFileName = properties.AfterUrl.Split('/')[1];
string fileType = listItem["FileType"].ToString();
if (!afterFileName.Contains(fileType))
{
string newFileName = validateFileName(afterFileName, fileType);
listItem["Name"] = newFileName;
try
{
this.EventFiringEnabled = false;
listItem.File.Update();
listItem.SystemUpdate(true);
}
finally
{
this.EventFiringEnabled = false;
}
}
}