Friday 11 July 2014

Load Attachments from List

public void ShowAttachment(string ListItemID, PlaceHolder PlaceHolderObj)
{
//Impersonating the user to perform this action
WindowsImpersonationContext ctx = null;
RevertToSelf();
SPSite siteCollection = null;
SPWeb topLevelSite = null;
SPList list = null;
string SPSiteCollection = string.Empty;
string SPTopLevelSite = string.Empty;
string SPListName = string.Empty;
string SPListSubFolderName = string.Empty;
string strSPListAttachmentLocation = string.Empty;
string strFileName = string.Empty;
int intID = 0;
SPSiteCollection = System.Configuration.ConfigurationManager.AppSettings["SPSite"];
SPTopLevelSite = System.Configuration.ConfigurationManager.AppSettings["TopLevelSite"];
SPListName = System.Configuration.ConfigurationManager.AppSettings["ListName"];
SPListSubFolderName = System.Configuration.ConfigurationManager.AppSettings["FolderName"];
strSPListAttachmentLocation = System.Configuration.ConfigurationManager.AppSettings["SPListAttachmentLocation"];
try
{
ctx = WindowsIdentity.GetCurrent().Impersonate();
using (SPSite site = new SPSite(SPSiteCollection))
{
//using (SPWeb web = site.OpenWeb(SPTopLevelSite))
using (SPWeb web = site.AllWebs[SPTopLevelSite])
{
web.AllowUnsafeUpdates = true;
list = web.Lists[SPListName];
SPListItem item = list.GetItemById(Convert.ToInt32(ListItemID.ToString().Trim()));
SPAttachmentCollection attachments = item.Attachments;
if (attachments.Count > 0)
{
SPFolder folder = web.Folders["Lists"].SubFolders[SPListSubFolderName].SubFolders["Attachments"].SubFolders[item["ID"].ToString()];
foreach (SPFile objSPFile in folder.Files)
{
if (folder.Files.Count != 0)
{
strFileName = strSPListAttachmentLocation + objSPFile.ToString().Replace(" ", "%20");
HyperLink objHyperLink = new HyperLink();
objHyperLink.NavigateUrl = strFileName.Trim();
objHyperLink.Text = objSPFile.Name.ToString();
objHyperLink.ID = intID.ToString();
intID++;
string strFileExt = String.Empty;
strFileExt = objSPFile.Name.ToString().Substring(objSPFile.Name.ToString().LastIndexOf(".") + 1);
if (strFileExt.ToUpper().Equals("PDF"))
{
objHyperLink.Target = "_blank";
}
PlaceHolderObj.Controls.Add(objHyperLink);
PlaceHolderObj.Controls.Add(new LiteralControl("
"));
}
}
}
}
}
}
catch (Exception ex)
{
throw ex;
}
finally
{
if (topLevelSite != null)
{
topLevelSite.AllowUnsafeUpdates = false;
topLevelSite.Dispose();
}
if (siteCollection != null)
siteCollection.Dispose();
// Ensure impersonation is reverted
if (ctx != null)
ctx.Undo();
}
}