使用SharePoint客户端对象模型重命名文件?

时间:2013-03-15 11:45:22

标签: sharepoint-2010 sharepointdocumentlibrary sharepoint-clientobject

这似乎是一个愚蠢的问题,但我似乎无法在Google上找到任何答案。

我编写了一种查询SharePoint的方法,并根据我指定的文档名称参数重命名文档。我使用了类似的方法重命名文件夹,这已经工作正常但是当我尝试重命名文件时,我得到了一个ArgumentOutOfRangeException

这是我的代码:

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;
            }
        }
    }  

任何有关此的帮助将不胜感激。谢谢!

1 个答案:

答案 0 :(得分:1)

您需要使用ListItems文件成员:

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