How to delete old versions of a document from a document library?

Create a console application and add the reference if Microsoft.SharePoint .
Add the web reference of version’s (http://MossSite/_vti_bin/versions.asmx) web service.

 

    1: //Change the SPSite URL.
    2:            using (SPSite site = new SPSite(http://MossSite/sites/SiteCollection))
    3:            {
    4:                using (SPWeb web = site.OpenWeb())
    5:                {
    6:                    //Change the Document Library Name.
    7:                    SPDocumentLibrary library = (SPDocumentLibrary)web.Lists["MATTDOCLibrary"];
    8:                    foreach (SPListItem item in library.Items)
    9:                    {
   10:                        Console.WriteLine(item.Name);
   11:                        Console.WriteLine("====== BEFORE DELETION =====\n\n");
   12:                        SPFile file = (SPFile)item.File;
   13:                        int counter = item.Versions.Count;
   14:                        Console.WriteLine("counter :- " + counter);
   15:                        VersionService.Versions objVersion = new VersionService.Versions();
   16:                        objVersion.Credentials = System.Net.CredentialCache.DefaultCredentials;
   17:                        System.Xml.XmlNode ndVersion = objVersion.DeleteAllVersions(item.File.ToString());
   18:                    }
   19:                    library.Update();
   20:                    web.Update();
   21:                    foreach (SPListItem item in library.Items)
   22:                    {
   23:                        Console.WriteLine("\n" + item.DisplayName);
   24:                        Console.WriteLine("======AFTER DELETION =====\n\n");
   25:                        foreach (SPListItemVersion subitem in item.Versions)
   26:                        {
   27:                            Console.WriteLine("Version ID : " + subitem.VersionLabel.ToString());
   28:                        }
   29:                    }
   30:                }
   31:            }