Deleting a file from sharepoint using web service

sharepointweb services

I am trying to delete a file from a sharepoint document library.
My application is in C#, which uses the web services of sharepoint.
Would like to know how this can be done.
Thanks in advance.

Best Answer

Delete a Document in SharePoint using Web Services

1.Add Web Reference to http://[your site]/_vti_bin/Lists.asmx

2.You need Document ID, Library Name, and Url to the document to be deleted

var spWebServiceLists = "http://[your site]/_vti_bin/Lists.asmx";
var listService = new Lists
{
    Credentials = CredentialCache.DefaultCredentials,
    Url = spWebServiceLists
};

string id = 10;
string library = @"Shared Documents";
string url = @"http://[your site]/Shared Documents/Test.docx";
string xml = "<Method ID='1' Cmd='Delete'>" + 
             "<Field Name='ID'>" + id + "</Field>" +
             "<Field Name='FileRef'>" + HttpUtility.UrlDecode(url) + "</Field>" +
             "</Method>";

/*Get Name attribute values (GUIDs) for list and view. */
System.Xml.XmlNode ndListView = listService.GetListAndView(library, "");
string strListID = ndListView.ChildNodes[0].Attributes["Name"].Value;
string strViewID = ndListView.ChildNodes[1].Attributes["Name"].Value;

/*Create an XmlDocument object and construct a Batch element and its
attributes. Note that an empty ViewName parameter causes the method to use the default view. */
System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
System.Xml.XmlElement batchElement = doc.CreateElement("Batch");
batchElement.SetAttribute("OnError", "Continue");
batchElement.SetAttribute("ListVersion", "1");
batchElement.SetAttribute("ViewName", strViewID);

/*Specify methods for the batch post using CAML. To update or delete, 
specify the ID of the item, and to update or add, specify 
the value to place in the specified column.*/
batchElement.InnerXml = xml;

XmlNode item;
item = listService.UpdateListItems(library, batchElement);

I just tested this code and works well.

For more information please see following links

Lists.UpdateListItems Method

How to: Update List Items