When renaming a file in SharePoint via client object model, the filename gets trimmed if there's a dot in between
Asked Answered
C

1

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?

Collector answered 30/10, 2014 at 9:55 Comment(0)
S
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");
}
Snubnosed answered 3/11, 2014 at 9:4 Comment(2)
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);Collector
Does this method preserve the version history?Convolute

© 2022 - 2024 — McMap. All rights reserved.