I am at my wits end on this one. I have a user interface that creates and edits documents stored in a SharePoint document library. The trick part is I need to allow the user to update the document no problem just use SPFile.SaveBinary()
right?
This definitely updates the contents of the file but somehow the old file name and the old extension persist, this is a problem. Deleting and re-adding the list item is not a solution either because the id of the item is being referenced in the url.
My question is how can I update the extension and filename metadata of the SPFile item?
So far all of my attempts using the object library have failed, i've tried updating the fields below none have been successful. It seems like there has to be an easier way to do this.
SPFile file = item.File;
file.Item[SPBuiltInFieldId.FileLeafRef] = resolvedFileName;
file.Item[SPBuiltInFieldId.FileRef] = "/File/" + resolvedFileName;
file.Item[SPBuiltInFieldId.BaseName] = System.IO.Path.GetFileNameWithoutExtension(resolvedFileName);
file.Item["Name"] = System.IO.Path.GetFileNameWithoutExtension(resolvedFileName);
file.SaveBinary(conduitFile);
file.Update();
[EDIT] - Here is my working solution.
SPFile file = item.File;
string resolvedFileName = item.ID.ToString() + "-" + conduitFileName;
item["Title"] = resolvedFileName;
file.SaveBinary(conduitFile);
file.MoveTo(item.ParentList.RootFolder.Url + "/" + resolvedFileName, true);
file.Item["Name"] = resolvedFileName;
file.Update();
After the file is saved to the library, use the MoveTo
method and pass the modified file name in the newUrl
parameter.
SPFile.MoveTo Method (String)
Quick & Easy: Rename Uploaded File Using SharePoint Object Model Via an Event Receiver