Wednesday, 23 April 2014

Delete attachment form SharePoint

Delete attachment form SharePoint
public void DeleteUploadedFile(string fileName, string strUARID)
{
WindowsIdentity wi = WindowsIdentity.GetCurrent();
WindowsImpersonationContext ctx = null;
RevertToSelf();
 
SPSite objSPSite = null;
SPWeb objSPWeb = null;
SPList objSPList = null;
SPQuery oquery = null;
 
string InFile = String.Empty;
string CompairFile = String.Empty;
string attachFileName = string.Empty;
 
SPListItemCollection myitems = null;
SPAttachmentCollection attachments = null;
 
try
{
ctx = WindowsIdentity.GetCurrent().Impersonate();
 
objSPSite = new SPSite(System.Configuration.ConfigurationManager.
AppSettings["SPDocumentLibrary"]);
objSPWeb = objSPSite.AllWebs[System.Configuration.ConfigurationManager.
AppSettings["TopLevelSite"]];
objSPList = objSPWeb.Lists[System.Configuration.ConfigurationManager.
AppSettings["ListName"]];
objSPSite.OpenWeb();
objSPSite.AllowUnsafeUpdates = true;
objSPWeb.AllowUnsafeUpdates = true;
 
//Create an instance of SPQuery Object
oquery = new SPQuery();
//Specify the condition
oquery.Query = “” + strUARID.Trim() + “”;
//Set the row limit
oquery.RowLimit = 1;
 
//Assign the query object to myitems List Collection
myitems = objSPList.GetItems(oquery);
foreach (SPListItem item in myitems)
{
attachments = item.Attachments;
if (attachments.Count > 0)
{
SPFolder folder = objSPWeb.Folders["Lists"].SubFolders[System.Configuration.
ConfigurationManager.AppSettings["FolderName"]].SubFolders["Attachments"].
SubFolders[item["ID"].ToString()];
foreach (SPFile file in folder.Files)
{
attachFileName = file.ToString().Replace(“/”, “\\”);
InFile = fileName.ToString();
CompairFile = attachFileName.ToString().Substring(attachFileName.ToString().
LastIndexOf(“\\”) + 1);
 

if (CompairFile.Trim().ToUpper() == InFile.Trim().ToUpper())
{
file.Delete();
break;
}
}
}
}
}
catch (Exception ex)
{
throw ex;
}
finally
{
objSPSite.AllowUnsafeUpdates = false;
objSPWeb.AllowUnsafeUpdates = false;
objSPSite.Dispose();
objSPWeb.Dispose();
// Ensure impersonation is reverted
ctx.Undo();
}
}