Wednesday 7 May 2014

SharePoint Download 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 functionality 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();
}
Now set these sessions to null.
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;
}
}