Question

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();
Was it helpful?

Solution

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

OTHER TIPS

Another way that is simpler than using the MoveTo is to use the BaseName property of the SPListItem. You would set this by running

item["BaseName"] = resolvedFileName; //Whatever you want the new file name to be 
item.Update();

This is easier than MoveTo because you don't have to worry about the folder hierarchy and you don't have to worry about the file extension.

For some reason the property is not listed on the MSDN documentation, but it seems to work well without a problem.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top