Wednesday, April 28, 2010

How to delete a file from SharePoint document library.

To delete a file and all its versions from a document library where you know only the file name and not the item id etc, there is no other way but to loop through the file collection returned by "Library.File" and break the loop once you find and delete the file.

Here is the example



public void DeleteFile(string FinalFileName)
{
string s_FileName = "";
//Get the library name from webconfig file
string doclibname = ConfigurationManager.AppSettings["doclibname"].ToString();
//Get site object
SPSite objSite = SPContext.Current.Site;
SPWeb objWeb = objSite.OpenWeb();
//Get the library
SPFolder mylibrary = objWeb.Folders[doclibname];
foreach (SPFile file in mylibrary.Files)
{
if (file.Name.ToString().ToUpper() == FinalFileName.ToUpper())
{
//delete the file and exit the loop
objWeb.AllowUnsafeUpdates = true;
file.Delete();
mylibrary.Update();
objWeb.AllowUnsafeUpdates = false;
break;

}
}

}



Thanks
Sanjay Tiwari
Dallas, Texas

No comments: