9

I wrote a small application using the SharePoint client object model, which renames all files inside a SharePoint 2010 document library. Everything works well, except if the filename should contain a dot somewhere in between, it get's trimmed, starting with the dot.

For example, when the new filename should be "my fi.le name" it ends up with "my fi" in SharePoint. The extension of the file (.pdf in my case) stays correct by the way.

Here's what I'm doing (in general):

ClientContext clientContext = new ClientContext("http://sp.example.com/thesite);
List list = clientContext.Web.Lists.GetByTitle("mydoclibrary");
ListItemCollection col = list.GetItems(CamlQuery.CreateAllItemsQuery());
clientContext.Load(col);
clientContext.ExecuteQuery();

foreach (var doc in col)
{
    if (doc.FileSystemObjectType == FileSystemObjectType.File)
    {
        doc["FileLeafRef"] = "my fi.le name";
        doc.Update();
        clientContext.ExecuteQuery();
    }
}

When I'm renamig the file in SharePoint manually via browser (edit properties), everything works as it should: The dot stays and the filename won't be trimmed at all.

Is "FileLeafRef" the wrong property? Any ideas what's the cause here?

Pandora
  • 233
  • 1
  • 6
  • 15

1 Answers1

19

Using FileLeafRef property it is possible to update file name but without extension.

How to rename file using SharePoint CSOM

Use File.MoveTo method to rename a file:

public static void RenameFile(ClientContext ctx,string fileUrl,string newName)
{
        var file = ctx.Web.GetFileByServerRelativeUrl(fileUrl);
        ctx.Load(file.ListItemAllFields);
        ctx.ExecuteQuery();
        file.MoveTo(file.ListItemAllFields["FileDirRef"] + "/" + newName, MoveOperations.Overwrite); 
        ctx.ExecuteQuery();
}

Usage

using (var ctx = new ClientContext(webUrl))
{
    RenameFile(ctx, "/Shared Documents/User Guide.docx", "User Guide 2013.docx");
}
Vadim Gremyachev
  • 57,952
  • 20
  • 129
  • 193
  • 3
    Thanks! That actually worked :-) It's possible to add the extension, by using **file.ListItemAllFields["File_x0020_Type"]** like: `file.MoveTo(file.ListItemAllFields["FileDirRef"] + "/" + newName + file.ListItemAllFields["File_x0020_Type"], MoveOperations.Overwrite);` – Pandora Nov 03 '14 at 09:39
  • Does this method preserve the version history? – Tyson Gibby Oct 26 '22 at 19:19