Josh Price
Josh Price

Reputation: 259

Rename File Using SharePoint Client Object Model?

This may seem like a stupid question but I can't seem to find any answers on Google.

I have written a method to query SharePoint and rename a document based on the document name parameter I specify. I have used a similar method to rename folders and this has worked fine however when I try to rename a file I get an ArgumentOutOfRangeException

Here is my code:

public bool RenameFileInDocumentLibrary(string documentName, string newDocumentName, ClientContext clientContext)
        {
            {
                bool isDocumentRenamed = false;

                string url = "MySharePointSite";

                List list = clientContext.Web.Lists.GetByTitle("MyDocLib");

                CamlQuery query = new CamlQuery();
                query.ViewXml = "<View Scope=\"RecursiveAll\"> " +
                            "<Query>" +
                                "<Where>" +
                                    "<And>" +
                                        "<Eq>" +
                                            "<FieldRef Name=\"FSObjType\" />" +
                                            "<Value Type=\"Integer\">2</Value>" +
                                         "</Eq>" +
                                          "<Eq>" +
                                            "<FieldRef Name=\"Title\"/>" +
                                            "<Value Type=\"Text\">" + documentName + "</Value>" +
                                          "</Eq>" +
                                    "</And>" +
                                 "</Where>" +
                            "</Query>" +
                            "</View>";

                var files = list.GetItems(query);

                clientContext.Load(list);
                clientContext.Load(list.Fields);
                clientContext.Load(files, fs => fs.Include(fi => fi["Title"],
                    fi => fi["DisplayName"],
                    fi => fi["FileLeafRef"]));
                clientContext.ExecuteQuery();

                if (files.Count == 0)
                {
                    files[0]["Title"] = newDocumentName;
                    files[0]["FileLeafRef"] = newDocumentName;
                    files[0].Update();
                    clientContext.ExecuteQuery();
                    isDocumentRenamed = true;
                }

                return isDocumentRenamed;
            }
        }
    }  

Any help with this would be appreciated. Thanks!

Upvotes: 2

Views: 2928

Answers (1)

VB Did Nothing Wrong
VB Did Nothing Wrong

Reputation: 385

You need to use the ListItems File member:

string newPath = files[0]["FileDirRef"] + "/" + "MyNewFileName" + ".extension";
files[0].File.MoveTo(newPath, MoveOperations.Overwrite);
files[0].Update();
clientContext.ExecuteQuery();

Upvotes: 2

Related Questions