Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SharePoint SPFile change extension on existing item possible?

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();
like image 857
James Avatar asked Feb 04 '11 07:02

James


2 Answers

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

like image 200
Marek Grzenkowicz Avatar answered Oct 25 '22 12:10

Marek Grzenkowicz


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.

like image 45
Peter Jacoby Avatar answered Oct 25 '22 13:10

Peter Jacoby