Sunday 27 September 2015

Programmatically Adding, Deleting, Copying and Downloading Attachments in SPList


1. ADDING AN ATTACHMENT TO AN ITEM IN SPLIST

string _Str_File_Name = FileUpload1.PostedFile.FileName;
            byte[] contents = GetFileStream();
            int itemId = 0;
            using (SPSite site = new SPSite(SPContext.Current.Web.Url.ToString()))
            {
                using (SPWeb web = site.OpenWeb())
                {
                    SPList list = web.Lists["Check"];
                    web.AllowUnsafeUpdates = true;
                    SPListItem item = list.Items.Add();
                    item["Title"] = "Title1";
                    item["Citys1"] = "CCC1";
                    if ((_Str_File_Name != null) && (contents.Length > 0))
                    {
                        SPAttachmentCollection fileAttach = item.Attachments;
                        fileAttach.Add(_Str_File_Name, contents);
                    }
                    item.Update();
                    itemId = item.ID;
                }
            }

2.  DELETING AN ATTACHMENT FROM SPLIST :
private void DeleteAttachment(int NodeID)
 {
 try
 {
 SPList myList = SPContext.Current.Web.Lists[“Item List”];
SPListItem delItem = myList.GetItemById(NodeID);
 SPAttachmentCollection atCol = delItem.Attachments;
 if (delItem[“Attached FileName”] != null)
 {
 string strFileName = delItem[“Attached FileName”].ToString();
 delItem[“Attached FileName”] = string.Empty;
 atCol.Delete(strFileName);
 delItem.Update();
 }
 }
 catch (Exception eDel)
 {
 string errDel = eDel.Message;
 }
 }
3. DOWNLOADING THE ATTACHMENT :

Find the download link first then reedirect to another aspx page so that the response ending on the current page does not affect the functionalities on this :-
private void DownloadAttachment(int NodeID)
{
try
{
string AttachmentURL = string.Empty;
SPList myList = SPContext.Current.Web.Lists[“Item List”];
SPListItem attItem = myList.GetItemById(NodeID);
if (attItem[“Attached FileName”] != null)
{
AttachmentURL = “/Lists/Item%20List1/Attachments/” + NodeID.ToString() + “/” + attItem[“Attached FileName”].ToString();
System.Web.HttpContext.Current.Session[“FileName”] = attItem[“Attached FileName”].ToString();
System.Web.HttpContext.Current.Session[“Attachment”] = AttachmentURL.Trim();
}
else
{
lblReport.Text = GetMessage(110);
}
if (AttachmentURL != string.Empty)
Page.Response.Write(“”);
}
catch (Exception eDwn)
{
string errDwn = eDwn.Message;
}
}
At the aspx page you need to run the code as :
if(System.Web.HttpContext.Current.Session[“Attachment”] != null)
{
string strName = System.Web.HttpContext.Current.Session[“FileName”].ToString();
string sbURL = System.Web.HttpContext.Current.Session[“Attachment”].ToString();
System.Web.HttpResponse response;
response = System.Web.HttpContext.Current.Response;
System.Web.HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.Default;
response.AppendHeader(“Content-disposition”, “attachment; filename=” + strName);
response.AppendHeader(“Pragma”, “cache”);
response.AppendHeader(“Cache-control”, “private”);
response.Redirect(sbURL);
response.End();
}

4. COPYING AN ATTACHMENT FROM ONE ITEM TO ANOTHER IN SPLIST :
private void CopyAttachment(int FromID, int NodeID, string AttachedFile)
 {
 try
 {
 SPList myList = SPContext.Current.Web.ParentWeb.Lists[“Item List”];
SPListItem myItem = myList.GetItemById(NodeID);
 SPListItem myPrevItem = myList.GetItemById(FromID);
SPAttachmentCollection attColl = myPrevItem.Attachments;
SPFile attFile = myPrevItem.ParentList.ParentWeb.GetFile(myPrevItem.Attachments.UrlPrefix + AttachedFile);
 string fileRead = myPrevItem.Attachments.UrlPrefix.ToString() + AttachedFile;
StreamReader fsReader = new StreamReader(attFile.OpenBinaryStream());
 Stream fStream = fsReader.BaseStream;
byte[] contents = new byte[fStream.Length];
fStream.Read(contents, 0, (int)fStream.Length);
fStream.Close();
 fStream.Dispose();
myItem.Attachments.Add(AttachedFile, contents);
 myItem.Update();
 }
 catch (Exception eCopy)
 {
 string errCopy = eCopy.Message;
 }
}

1 comment:

  1. Thanks for providing the code
    http://staygreenacademy.com/sharepoint-2013-training/

    ReplyDelete