Rename a File in a SharePoint document library through Client object model

Hi,
How  to Rename a File in a SharePoint document library through Client object model?
Thanks
Poomani Sankaran

Hi,
According to your description, you want to rename file in the document library using SharePoint Client Object Model.
Here is a code snippet works well in my environment for your reference:
static void Main(string[] args)
string url = "http://sp2013sps/sites/test/";
ClientContext clientContext = new ClientContext(url);
Microsoft.SharePoint.Client.List spList = clientContext.Web.Lists.GetByTitle("Documents");
clientContext.Load(spList);
clientContext.ExecuteQuery();
if (spList != null && spList.ItemCount > 0)
Microsoft.SharePoint.Client.CamlQuery camlQuery = new CamlQuery();
camlQuery.ViewXml =@"<View> <Query> <Where><Eq><FieldRef Name='LinkFilenameNoMenu' /><Value Type='Computed'>New Microsoft Word Document.docx </Value></Eq></Where> </Query> <ViewFields><FieldRef Name='Title' /></ViewFields> </View>";
ListItemCollection listItems = spList.GetItems(camlQuery);
clientContext.Load(listItems);
clientContext.ExecuteQuery();
listItems[0]["Title"] = "word.docx";
listItems[0]["FileLeafRef"] = "word.docx";
listItems[0].Update();
clientContext.ExecuteQuery();
More information about SharePoint Client Object Model:
http://msdn.microsoft.com/en-us/library/office/ee537247(v=office.14).aspx
http://www.codeproject.com/Articles/399156/SharePoint-Client-Object-Model-Introduction
http://www.learningsharepoint.com/2010/07/12/programmatically-upload-document-using-client-object-model-sharepoint-2010/
Best regards

Similar Messages

  • Error in Application.Run(DisplayLoginForm) and Remote Authentication in SharePoint Online Using the Client Object Model

    Hi guys
    I Think that is a simple error, but I don’t have enough knowledge in .NET apps.
    I make an console app that use Remote Authentication in SharePoint Online Using the Client Object Model, that a I downloaded from MSDN.
    This App run ok.
    But when I like to make a Windows From App. This component send me an error in Application.Run(DisplayLoginForm)
    This err msg :
     An unhandled exception of type 'System.InvalidOperationException' occurred in System.Windows.Forms.dll
    Additional information: Starting a second message loop on a single thread is not a valid operation. Use Form.ShowDialog instead.
    Is there any way to use a form inside a windows form?
    Thank in advance
    Ramiro
    Ramiro B

    Hi,
    Based on the error message, please do as following:
    1. Check your code logic below:
    void btn_Click(object sender, System.EventArgs e)
    Thread t = new Thread(StartMyForm);
    t.TrySetApartmentState(ApartmentState.STA);
    t.Start();
    public static void StartMyForm()
    Application.Run(new MyForm(..));
    2.Try to add the following code line in your code.
    Application.Restart();
    If the issue still exists, please provide your requirement and code for a further research.
    Best Regards
    Dennis Guo
    TechNet Community Support

  • Fetching file size using CAML query in Javascript client object model

    Hi,
    I am using the Javascript client object model to retrieve contents of a document library.
    I have a document library, which contains a folder "Folder1" . "Folder1" has a zip file. I would like to get the file size of the zip file.
    I have tried the below code, but not sure, how to fetch the file size.
    function FetchImage() {
    var clientcontext = new SP.ClientContext.get_current();
    var oweb = clientcontext.get_web();
    var olibrary = oweb.get_lists().getByTitle(DocLibrary);
    var query = new SP.CamlQuery();
    query.set_folderServerRelativeUrl("Lists/DocLibrary/folder1/");
    folder = olibrary.getItems(query);
    clientcontext.load(folder, 'Include(Title,ContentType, FileLeafRef,FileDirRef,File)');
    clientcontext.executeQueryAsync(Function.createDelegate(this, this.RenderDataOnSuccess), Function.createDelegate(this, this.RenderDataOnFailure));
    function RenderDataOnSuccess() {
    var ListEnumerator = this.folder.getEnumerator();
    while (ListEnumerator.moveNext()) {
    var currentItem = ListEnumerator.get_current();
    if (_contentType.get_name() != "Folder") {
    var File = currentItem.get_file();
    if (File != null) {
    // Fetch file size
    How to fetch the file size?
    Thanks

    <script>
    function getSize()
            var myFSO = new ActiveXObject("Scripting.FileSystemObject");
            var filepath = document.upload.file.value;
            var thefile = myFSO.getFile(filepath);
            var size = thefile.size;
            alert(size + " bytes");
    </script>
    http://social.msdn.microsoft.com/Forums/en-US/e5d2ff3d-01c7-4cc0-a081-29a4dfbb0fad/getting-the-sharepoint-list-attachment-size-using-javascript?forum=sharepointcustomizationlegacy

  • SharePoint Online / Office 365 -- Client Object Model

    Hello,
    i try to get some Data from the SharePoint Online "Office365" Beta with the Client Object Model. I use an Sample from the MSDN but i always get the Error
    "Server was unable to process request. ---> The server was unable to process the request due to an internal error. ...." in Visual Studio 2010.
    Following the Code Snip:
    ClientContext clientContext = new ClientContext("https://URI.sharepoint.com/");
    clientContext.AuthenticationMode = ClientAuthenticationMode.FormsAuthentication;
    clientContext.FormsAuthenticationLoginInfo = new FormsAuthenticationLoginInfo("USER", "PASS");
    Web web = clientContext.Web;
    ListCollection allLists = web.Lists;
    clientContext.Load(web);
    clientContext.Load(allLists);
    clientContext.ExecuteQuery();
    Console.WriteLine("{0} ({1})", web.Title, web.Description);
    foreach (List list in allLists)
    Console.WriteLine("{0} ({1})", list.Title, list.BaseType);

    Hi M.Litschke. You should have received a welcome email when you signed up for the Beta that had the community forum link & login details in it. Did you not recieve one?Myles Jeffery | Thinkscape |
    SharePoint Online Deployment |
    SharePoint Online File Migration Tool

  • Attach a custom content type and set as default for picture library using client object model

    Hi,
    How to associate custom content type to a picture libraray and set it as default using the client object model?
    Thanks

    Hello,
    Here you go:
    http://social.msdn.microsoft.com/Forums/sharepoint/en-US/b1de0697-0006-4f89-8909-1b94aa18ad89/how-to-reorder-content-types-in-list-with-client-context
    http://www.niteenbadgujar.com/2013/05/change-default-content-type.html
    Hope it could help
    Hemendra:Yesterday is just a memory,Tomorrow we may never see
    Please remember to mark the replies as answers if they help and unmark them if they provide no help

  • How to execute XML batch commands using SharePoint Web services or Client Object Model

    Hi,
    I have a requirement to execute some batch commands to update SharePoint View Style, how can i do it using SharePoint webservices or SharePoint Client Object model.
          I need to execute the following Batch command over a particular web.
    <Method ID="UpdateView">
      <SetVar Name="Cmd">UpdateView</SetVar>
      <SetList Scope="Request">{GUID of List}</SetList>
      <SetVar Name="View">{GUID of View}</SetVar>  
      <SetVar Name="ViewStyle">6</SetVar>
      <SetVar Name="RowLimit">100</SetVar>
      <SetVar Name="Paged">TRUE</SetVar>
    </Method>

    Hi
    I tried it already... But UpdateView Method in the Views.asmx and Lists.asmx, both are not supporting for updating the style of the view (like Boxed, Newsletter...).
    If you have any code sample which will do this job with any of the SharePoint web services, please share it..

  • How to keep original Uploaded File Name in SharePoint Document Library?

    HI,
    I have document library. After Uploaded the file in document library. I want to keep the file name in some other filed.
    Why because in future i may change the file name in document library so in order to know the original name of the file.
    I want to do without any workflow. Is there any other default column like that?
    How could i achieve it?
    Thanks & Regards
    Poomani Sankaran

    Hello,
    Here is list of operations for file element, and you can save it in library column:
    http://social.technet.microsoft.com/wiki/contents/articles/22156.sharepoint-2010-a-complete-list-of-spfile-operations-using-ecma-script.aspx
    http://sprider.org/2011/12/13/sharepoint-ecmascript-to-adddeleteupdateget-list-items/
    Hemendra:Yesterday is just a memory,Tomorrow we may never see
    Please remember to mark the replies as answers if they help and unmark them if they provide no help

  • Download older version of a file from SharePoint Document Library using CSOM and 404 error

    Hi,
    I am trying to download previous versions including Major and Minor versions of documents from SharePoint Online using CSOM. I get 404 error when I try to download the file. I found several posts on various discussion forums where people are getting same
    error but none of those have any solution/answer. Below is one of the threads and sample code I have tried that results in 404 error. If I use the link in browser directly, I am able to download the file. Also I am able to download the current version of file
    using CSOM without any problem, it is only the older versions that give me 404 in CSOM.
    http://qandasys.info/how-to-download-the-historical-file-version-content-using-csom/
    public int GetStreamFromFile(string docid, string lib, string fileurl, ClientContext clientContext, int iuserid, string Version, bool isCurrrent)
    if(!isCurrent)
    List LibraryName = clientContext.Web.Lists.GetByTitle(lib);
    clientContext.Load(LibraryName);
    clientContext.ExecuteQuery();
    CamlQuery camlQuery = new CamlQuery();
    camlQuery.ViewXml = "" + fileurl +
    Microsoft.SharePoint.Client.ListItemCollection collListItem = LibraryName.GetItems(camlQuery);
    clientContext.Load(collListItem, items => items.Include(item => item.Id, item => item["FileLeafRef"], item => item["LinkFilename"],
    item => item["FileRef"], item => item["File_x0020_Size"], item => item["DocIcon"], item => item.File.Versions));
    //clientContext.Load(collListItem);
    clientContext.ExecuteQuery();
    foreach (Microsoft.SharePoint.Client.ListItem oListItem in collListItem)
    //string fileurl1 = (string)oListItem["FileRef"];
    //string filename = (string)oListItem["LinkFilename"];
    foreach (FileVersion version in oListItem.File.Versions)
    if (Version == version.VersionLabel)
    //Added excutequery to get object one more time as per blog
    //http://social.technet.microsoft.com/Forums/de-DE/sharepointdevelopmentprevious/thread/88a05256-8694-4e40-863d-6c77512e079b
    clientContext.ExecuteQuery();
    FileInformation fileInformation = ClientOM.File.OpenBinaryDirect(clientContext,version.Url);
    bytesarr = ReadFully(fileInformation.Stream);
    Darwaish

    Hi,
    According to your description,
    I know you want to get older version of a file from SharePoint Document Library using Client Object Model.
    The following code snippet for your reference:
    public void GetVersions()
    ClientContext clientContext = new ClientContext(“http://SPSite”);
    Web site = clientContext.Web;
    clientContext.Load(site);
    clientContext.ExecuteQuery();
    File file = site.GetFileByServerRelativeUrl(“/Shared Documents/mydocument.doc”);
    clientContext.Load(file);
    clientContext.ExecuteQuery();
    ListItem currentItem = file.ListItemAllFields;
    clientContext.Load(currentItem);
    clientContext.ExecuteQuery();
    FileVersionCollection versions = file.Versions;
    clientContext.Load(versions);
    clientContext.ExecuteQuery();
    if (versions != null)
    foreach(FileVersion _version in versions)
    Console.WriteLine(“Version : {0}”,_version.VersionLabel);
    More information:
    http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.client.file.versions.aspx
    Best Regards,
    Dennis Guo

  • How to connect SharePoint Document Library with Local file system?

    Hi
    I have a SharePoint Document library and in my local system i have 3TB files. It is very difficult to upload 3TB files in SharePoint.
    I want a file details in SharePoint Document Library but physical file would be in local.
    While click the file in Document library. The document should open from local.
    Anyone help me on it.
    Thanks & Regards
    Poomani Sankaran

    Hi,
    your requirement doesn't work out-of-the-box as all data uploaded to SharePoint needs to be stored in SQL database. Thus in your case 3 TB of fileshare would need to move to SQL.
    In case you don't want to go this way, there are 3rd party vendors who offer Software like AvePoint Connector. Products like these use SQL RBS (Storage Externalization API) so that files remain in your file system but metadata is kept in SharePoint. If you
    need more information on that, please let me know.
    Regards,
    Dennis

  • Upload a document from a form into a SharePoint document library

    The idea is that I have a form which I want to allow users to upload files into my SharePoint document library. I am just not just what to do after the 'HasFile' Statement. Some small snippets of my code below. I am just not sure how from the fileupload ID
    to get it into my document library. Please provide code.
    <asp:FileUpload ID="FileUpload1" runat="server" />
    <asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />
    Server side code
    protected void Button1_Click(object sender, EventArgs e)
    if (FileUpload1.HasFile)

    protected
    void
    Button1_Click(object
    sender,
    EventArgs
    e)
       if
    (FileUpload1.HasFile)
            // Assuming you have list current context. Or else get reference to the list instance from the parent SPWeb     var list
    = SPContext.Current.List;
         list.RootFolder.Files.Add(FileUpload1.FileName,
    FileUpload1.FileBytes).Update();

  • How to rename the SharePoint Document Library existing file name using Web service

    Hi,
    How to rename the SharePoint Document Library existing file name using SharePoint Web service.
    Is it possible. How could i do it?
    Thanks & Regards
    Poomani Sankaran

    Hi,
    Lists.UpdateListItems Method
    would be helpful for your requirement.
    Here is a blog with code demo for your reference:
    http://blogs.msdn.com/b/knowledgecast/archive/2009/05/20/moss-using-the-list-web-service-to-rename-a-file.aspx
    Best regards,
    Patrick
    Patrick Liang
    TechNet Community Support

  • Upload/Download file to/from a document library in a SharePoint online site

    Hi,
    I am referring to the below blog for Upload/Download file to/from a document library in a SharePoint online site.
    http://blogs.msdn.com/b/rohitpuri/archive/2007/04/10/upload-download-file-to-from-wss-document-library-using-dav.aspx?CommentPosted=true#commentmessage
    I would like to know if this is feasible with a SharePoint online site.
    If feasible, how can I resolve the below exception I am getting while using the code.
    “The remote server returned an error: (403) Forbidden”.
    Thanks,
    Thanan

    Hi,
    Actually what I am trying to achieve is the two things.
    1) By using only the user's name, need to upload/download from/to the document library of SharePoint online site using the CSOM. (i.e., achieving Single Sign On / Windows Authentication)
    2) I need to achieve the above only by passing the document URL; not by hardcording/ configuring the document library name in the windows application.
    Can anyone pls help on this now?
    [Below code is working fine. But need to arrive the solution whereas the above 2 conditions are not violated.
    using (var clientContext
    = new ClientContext("https://yoursiteurl.com"))
               string passWd
    = "password";
               SecureString securePassWd
    = new SecureString();
               foreach
    (var c in passWd.ToCharArray())
                    securePassWd.AppendChar(c);
                clientContext.Credentials
    = new SharePointOnlineCredentials("username", securePassWd);
               using
    (var fs =
    new FileStream("fileName",
    FileMode.Open))
    var fi =
    new FileInfo("fileName");
    var list = clientContext.Web.Lists.GetByTitle("Doc Library");
                   clientContext.Load(list.RootFolder);
                   clientContext.ExecuteQuery();
    var fileUrl = String.Format("{0}/{1}", list.RootFolder.ServerRelativeUrl,
    fi.Name);
    Microsoft.SharePoint.Client.File.SaveBinaryDirect(clientContext, fileUrl,
    fs, true);
    Thanks,
    Thanann

  • Sharepoint document library file name column in content database?

    Hi,
    How to get a sharepoint document library file name column in content database?
    Thanks
    Poomani Sankaran

    You're not supposed to develop any solutions accessing the content database directly. It's not supported. Document Library Filename is stored in LeafName column, table: AllDocs.
    2.2.6.1 AllDocs Table
    This post is my own opinion and does not necessarily reflect the opinion or view of Slalom.

  • Some chinese character file name not uploading in SharePoint Document Library?

    Hi
    Some Chinese character pdf file name not uploading in SharePoint Document Library. I am getting following error.
    1. File not found error if i would upload using file browse option in Doc Lib.
    2. Can't read from the source file or disk. if i would tried to copy and paste using "Open with explorer" options.
    File name is "LA(未签署).pdf"
    Note: This file has been converted from "TIFF" to "PDF".
    Thanks & Regards
    Poomani Sankaran

    Hi Poomani,
    For troubleshooting your issue, please let's verify the followings:
    Whether other pdf file which are not converted from "TIFF" and contain Chinese char could be uploaded into the SharePoint Document library.
    Whether other pdf file which are converted from "TIFF" and don't contain Chinese char could be uploaded into the SharePoint Document library.
    Please upload these pdf files into other libraries, compare the result.
    Please check the log file to find more information about this issue. The path of the log file is:
    C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\LOGS.
    Best Regards,
    Wendy
    Wendy Li
    TechNet Community Support

  • How to filter the Files from SharePoint Document Library based upon cloumn value

    Hi
    I should filter the files from document library. I have column called "Print Status" for the document library the value would be either "Yes" or "No".
    Now i should filter out the files which has "Print Status" as a "Yes".
    I am using SPFolder and SPFile from SharePoint Object Model to traverse the file in doc library.
    How could i do it?
    My Sample code:
    foreach (SPFolder childFolder in folder.SubFolders)
      if (childFolder.Name != "Forms")
        AspControls.TreeNode trn = new System.Web.UI.WebControls.TreeNode(childFolder.Name, "", "~/_layouts/images/itdl.gif", childFolder.ServerRelativeUrl.ToString(), "");
        newNode = TraverseFiles(childFolder, trn);
                                // add the new node to the tree
                                rootNode.ChildNodes.Add(newNode);
                        // loop through the files
                        foreach (SPFile childFile in folder.Files)
                            // create a new node and add to the tree
                            AspControls.TreeNode childNode = new System.Web.UI.WebControls.TreeNode(childFile.Name + " (" + childFile.TimeLastModified.ToShortDateString()
    + ")", Convert.ToString(childFile.Item["ID"]), "~/_layouts/images/" + childFile.IconUrl, childFile.ServerRelativeUrl.ToString(), "");
                            rootNode.ChildNodes.Add(childNode);
    Thanks
    Poomani Sankaran.

    Why do you transvers the file an not use a camp query? In a CAML query you can filter the print status and are able to get all files and folder objects at once.
    Check out the following post: http://social.msdn.microsoft.com/Forums/sharepoint/en-US/8c45b5e2-1fb8-435c-a97d-1d8c6d288d4c/caml-query-to-query-all-the-files-and-folders-in-document-library?forum=sharepointdevelopmentprevious
    Kind regards
    Stefan
    http://www.n8d.at/blog
    Follow me on Twitter: StFBauer |
    n8design
    Microsoft Community Contributor 2011 / 2012
    MCTS - SharePoint / WSS Configuration and Development

Maybe you are looking for

  • Invokin SQL*Loader from a stored procedure

    I try to invoke SQL*LOADER from within a database package by using external C procedure (the procedure calls the system() C function) but the loader generates the following error in its log file : SQL*Loader -523: error -2 writing to file (STDERR) an

  • Weblogic 9.1 with toplink JPA - Problem creating entityManagerFactory

    I am using weblogic 9.1 with toplink jpa provider. I am getting the error while creating entityManagerFactory. Exception stack trace faces.FacesException: #{LogonMB.authenticateLogin}: javax.faces.el.EvaluationException: java.lang.ExceptionInInitiali

  • OVM Hard & Soft Partitioning and Pool Design?

    Greetings, We are designing an Oracle VM environment with extensive use of both hard and soft partitioning. We realize that hard partitioning is not supported with Live Migration, Distributed Resource Scheduler (DRS) or Distributed Power Management (

  • Vertical lines iphone 4s, guaranteed

    Hello, My iphone 4s has vertical lines. The lines cover the display completely,  they are colorful and across the entire screen. I didn't even drop or something else. I bought my phone 6 months ago and I have 2 years guarentee in Turkey but the autho

  • Monodevelop now unnessessarily depends on gnome(-sharp)

    I was going to upgrade monodevelop from 0.12 revision 1 to revision 2. Until now monodevelop depended on gtk-sharp and a few other sharp libraries. But suddenly gnome-sharp got introduced as a dependency. If I understand correctly, this is not actual