Friday 23 May 2014

Update Title field with the File name for all files in a document library in sharepoint 2010

The below code will get all the files from all the sub folders to update the Title in a document library

            string strSiteCollURL = txtSiteCollURL.Text.ToString();
            string strDocLibr = txtDocLib.Text.ToString();
            try
            {
                SPSite site = new SPSite(strSiteCollURL);
                SPWeb web = site.OpenWeb();
                web.AllowUnsafeUpdates = true;

                SPFolder listobj = web.GetFolder(strDocLibr);
                SPDocumentLibrary libr = listobj.DocumentLibrary;
                SPQuery query = new SPQuery();
                query.ViewAttributes = "Scope=\"Recursive\"";
                SPListItemCollection listcoll = libr.GetItems(query);
                foreach (SPListItem item in listcoll)
                {
                    string eXtension = Path.GetExtension(item.Name);
                    string fileName = item.Name;

                    if (fileName != "")
                    {
                        if (eXtension != null && eXtension != "")
                        {
                            fileName = fileName.Replace(eXtension, "");
                        }
                        item["Title"] = fileName;
                    }
                    item.SystemUpdate();
                }

                System.Windows.Forms.MessageBox.Show("Successfully Updated the Titles");
            }
            catch (Exception ex)
            {
                System.Windows.Forms.MessageBox.Show(ex.Message);
            }

2 comments:

  1. Can the same code be applied for 2013? what is the JS files included here?
    Can you please let me know the complete details.

    We have an excel with a set of old and new file names. We are manually replacing all the file names now in Sharepoint 2013. Any way that we can achieve it through scripts?

    ReplyDelete
    Replies
    1. Folloe below steps to acheive the necessary functionality

      1)Installexcel application first on the server where you are planning to ru the powershell script

      2)Open the excel application using powershell

      3)Open the corresponding sheet.

      4)loop through each row where column values are fixed for old and new file names (for ex: for (row=0;row<rowsrange.length; row++) { oldfilename = sheet[row,1];
      newfilename = sheet[row,2];
      update/replace old filename with new filename like fileName = fileName.Replace(oldfilename, newfilename);

      Delete