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.


Discover more from Nishant Rana's Weblog

Subscribe to get the latest posts sent to your email.

Unknown's avatar

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.”

Please share your thoughts

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Discover more from Nishant Rana's Weblog

Subscribe now to keep reading and get access to the full archive.

Continue reading

Power Platform Puzzles

D365 CRM, Power Platform Tips &Tricks

Power Spark

Power Spark By Shrangarika

Van Carl Nguyen

Exploration of Power Platform

My Trial

It is my experience timeline.

Power⚡Thomas

Sharing my knowledge and experience about the Microsoft Power Platform.

Arpit Power Guide

a guide to powering up community

Welcome to the Blog of Paul Andrew

Sponsored by Cloud Formations Ltd

Deriving Dynamics 365

Deriving Solutions and features on Power Platform/Dynamics 365

The CRM Ninja

Thoughts & musings from a Microsoft Business Applications Ninja!

D CRM Explorer

Learn about Microsoft Dynamics CRM Power Platform customization and implementation and other cool stuffs

Stroke // Jonas Rapp

I know pre-stroke. I will improve who I was.

Power Melange

Power Melange By Shalinee

Clavin's Blog - PPUG.ORG

AI - Power Automate - Power Apps - SharePoint Online - Azure - Nintex - K2 - Artificial Intelligence

Sat Sangha Salon

An Inquiry in Being

The Indoencers

The Influencers & Influences of Indian Music

Monika Halan's blog

Hand's-free money management

D365 Demystified

A closer look at Microsoft Dynamics 365.

Microsoft Mate (msftmate) - Andrew Rogers

Experienced consultant primarily focused on Microsoft Dynamics 365 and the Power Platform

Manmit Rahevar's Blog

One Stop Destination for Microsoft Technology Solutions

MG

Naturally Curious

Brian Illand

Power Platform and Dynamics 365

Steve Mordue

The Professional Paraphraser

Subwoofer 101

Bass defines your home theater

SQLTwins by Nakul Vachhrajani

SQL Server tips and experiences dedicated to my twin daughters.

Everything D365

Discovering Azure DevOps and D365 Business Applications

Tech Wizard

Lets do IT Spells

XRM Tricks (Power Platform & Dynamics CRM )

Power Platform & Dynamics CRM

CRM TIPS BY PRM

Mail to crmtipsbyprm@gmail.com for queries and suggestions

nijos.dev

Giving back to the community what I have learned

Power Platform Learning

Your Go-To Resource for Power Apps, Power Automate & More

xrm CRM Dynamics

Dynamics CRM Technical & Functional Info

Dynamics 365 Blogs - Explained in unique way

Sometimes you need to look at things from different perspective.