Helper Code to delete an existing document from a SharePoint document library.

In one my projects we had a requirement to programmatically delete document uploaded to SharePoint’s document library.

Below is the code we used to achieve that.

 

        // documentFullUrl would be :- http://server_name/sites/contact/volunteer/test.docx.
		// listName :- the display name of the list

		/// <summary>
        /// Deletes the existing document by URL.
        /// </summary>
        /// <param name="documentFullUrl">The document full URL.</param>
        /// <param name="listName">Name of the list.</param>
        public void DeleteExistingDocumentByUrl(string documentFullUrl, string listName)
        {
            //// Gets the file name with extension from the submitted document url
            string fileNameToBeDeleted = documentFullUrl.Substring(documentFullUrl.LastIndexOf("/") + 1);

            //// Removes the file name from url to get the folder name
            string folderUrl = documentFullUrl.Replace("/" + fileNameToBeDeleted, String.Empty);

            //// Get the file Id
            string fileId = this.GetListIdInSharePoint(listName, folderUrl, fileNameToBeDeleted);

            //// Delete the file
            if (!String.IsNullOrEmpty(fileId))
            {
                this.DeleteItem(fileId, documentFullUrl, listName);
            }
        }

		 /// <summary>
        /// Gets the list id of a file.
        /// </summary>
        /// <param name="documentLibraryName">Name of the document library.</param>
        /// <param name="folderUrl">The folder URL to search in e.g. "http://server_name/sites/contact/volunteer"</param>
        /// <param name="fileName">Name of the file to search for.</param>
        /// <returns></returns>
        public string GetListIdInSharePoint(string documentLibraryName, string folderUrl, string fileName)
        {
            this.CreateListService();

            //// Set up xml  doc for getting list of files under a folder
            XmlDocument doc = new XmlDocument();
            XmlElement queryOptions = doc.CreateElement("QueryOptions");
            queryOptions.InnerXml = "<Folder>" + folderUrl + "</Folder>";

            XmlNode listItemsNode = listService.GetListItems(documentLibraryName, null, null, null, null, queryOptions, null);

            XmlDocument xmlResultsDoc = new XmlDocument();
            xmlResultsDoc.LoadXml(listItemsNode.OuterXml);

            XmlNamespaceManager ns = new XmlNamespaceManager(xmlResultsDoc.NameTable);
            ns.AddNamespace("z", "#RowsetSchema");

            foreach (XmlNode row in xmlResultsDoc.SelectNodes("//z:row", ns))
            {
                if (fileName == row.Attributes["ows_LinkFilename"].Value)
                {
                    return row.Attributes["ows_ID"].Value;
                }
            }

            return String.Empty;
        }

        /// <summary>
        /// Deletes the item.
        /// </summary>
        /// <param name="listService">The list service.</param>
        /// <param name="fieldId">The field id.</param>
        /// <param name="fieldRef">The field ref.</param>
        /// <param name="listName">Name of the list.</param>
        public void DeleteItem(string fieldId, string fieldRef, string listName)
        {
            string strBatch = string.Empty;
            strBatch = "<Method ID='1' Cmd='Delete'>" + "<Field Name='ID'>" + fieldId + "</Field><Field Name='FileRef'>" + fieldRef + "</Field></Method>";

            this.CreateListService();
            XmlDocument xmlDoc = new System.Xml.XmlDocument();
            XmlElement batch = xmlDoc.CreateElement("Batch");
            batch.InnerXml = strBatch;

            XmlNode myNode = listService.UpdateListItems(listName, batch);
        }

Hope it helps.


Author: Nishant Rana

I love working in and sharing everything about Microsoft.NET technology !

3 thoughts on “Helper Code to delete an existing document from a SharePoint document library.”

Share your thoughts

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s