Thursday, February 21, 2008

Delete SharePoint Document Library Files Programmatically

Following on from this post on moving or copying SharePoint files with FrontPage Remote Procedure Calls (RPC), and this older post on remotely saving files to a SharePoint document library, the code below demonstrates how to remove files programmatically from a remote document library without using the SharePoint API. Documentation about the move method can be found here. The EscapeVectorChars method can be found in the original post. Obviously because this RPC method will remove documents from your site (potentially deleting them permanently), please use with appropriate caution!

Update: You can download a comprehensive c# class library to automate RPC calls - including removing files. See this blog post for more information.

        public static bool Remove(string webUrl, out string result, params string[] webRelativeUrls)
        {
            string method = "method=remove+documents%3a12.0.4518.1016&service_name=%2f&url_list=[{0}]";
            method = String.Format(method, GetStringVector(webRelativeUrls));
            try
            {
                using (WebClient webClient = new WebClient())
                {
                    webClient.Credentials = CredentialCache.DefaultCredentials;
                    webClient.Headers.Add("Content-Type", "application/x-vermeer-urlencoded");
                    webClient.Headers.Add("X-Vermeer-Content-Type", "application/x-vermeer-urlencoded");
                    result = Encoding.UTF8.GetString(webClient.UploadData(webUrl + "/_vti_bin/_vti_aut/author.dll", "POST", Encoding.UTF8.GetBytes(method)));
                    if (result.IndexOf("\n<p>message=successfully") < 0) //note: will show success even if document(s) did not exist on the server
                        throw new Exception(result);
                }
            }
            catch (Exception ex)
            {
                result = ex.Message;
                return false;
            }
            return true;
        }
 
        static string GetStringVector(string[] strings)
        {
            StringBuilder sb = new StringBuilder();
            foreach (string s in strings)
            {
                sb.Append(EscapeVectorChars(s));
                sb.Append(";");
            }
            return sb.ToString().TrimEnd(';');
        }

5 comments:

Anonymous said...

what is the parameter names webRelativeUrls, i'm not yet be able to delete the document.
Can i use the remove method with the Part-I.

txs8311 said...

The parameter webRelativeUrls is the url (or array of urls) of the file(s) you want to delete. For example, to delete the file "test.txt" in the document library "Docs" you could use the following code:

string result = "";
Remove("http://localhost", out result, "Docs/test.txt");

To delete 2 files:

string result = "";
Remove("http://localhost", out result, "Docs/test1.txt", "Docs/test2.txt");

Christoph said...

This is a great solution, but I have a problem to use this WebClient if I only get the full URL of the item to be deleted.

Is there a possibility to identify what part of a url is the webRelativeUrl-Part and the documentLibrary-Part?

A URL http://localhost/Subsite/DocLibraryName/SubFolderInDocLib/Document.txt can not be split in this two parts!?

txs8311 said...

Christoph,

There are a couple of ways of splitting the Url into file and web paths.

The urlToWebUrl will do this for you. The POST url for this method would be something like:

Uri uri = new Uri(url);
string webUrl = string.Format("{0}://{1}", uri.Scheme, uri.Authority);
string postUrl = webUrl + "/_vti_bin/shtml.dll/_vti_rpc";

A second approach is covered in this post - take a look at the GetWebURL method.

Unknown said...

Odd...I get successful return but the document is not deleted. Any idea why?