Archive for the ‘Attachments’ Category


foreach (SPListItem attachItem in list.Items)
{
if (Convert.ToString(attachItem[“Request Number”]) == Convert.ToString(this.Page.Request.QueryString[“reqno”]))
{
foreach (string fileName in attachItem.Attachments)
{
SPFile file = attachItem.ParentList.ParentWeb.GetFile(attachItem.Attachments.UrlPrefix + fileName);
writer.RenderBeginTag(HtmlTextWriterTag.Tr);
writer.AddAttribute(HtmlTextWriterAttribute.Target, “_blank”);
writer.AddAttribute(HtmlTextWriterAttribute.Href, file.ServerRelativeUrl);
writer.AddStyleAttribute(HtmlTextWriterStyle.FontSize, “12px”);
writer.RenderBeginTag(HtmlTextWriterTag.A);
writer.Write(file.Name);
writer.RenderEndTag();
flag = true;
}
break;
}
}

Advertisements

If you are using a custom newform.aspx then you will face difficulties in adding attachments. There are two scenarios

  1. If you make your own infopath forms/user control then you will not be having the attachments option
  2. If you remove any columns(Default for that list) using sharepoint designer , you will have the option for attachments but it will not work.

In this case you have to go for coding.

To add an attachment to an item we will access the item which needs a file to be attached to it and we will use item.Attachments.Add() method to actually attach the file.

Add a .net FileUpload control and a button to your page and on the buttonclick event write the following code.

public void btnSubmit_Click(object sender, EventArgs e)
{
bool flag=false;
Microsoft.SharePoint.Administration.SPWebApplication webApp = this.web.Site.WebApplication;
webApp.FormDigestSettings.Enabled = false;
SPList list = web.Lists[“ACBS Client Request”];

//Upload the file on the server.
fileUpload.PostedFile.SaveAs(Request.PhysicalApplicationPath + “UploadedFiles\\” + fileUpload.FileName);


FileInfo file = new FileInfo(Request.PhysicalApplicationPath + “UploadedFiles\\” + fileUpload.FileName);

foreach (SPListItem attachItem in list.Items)
{
if (Convert.ToString(attachItem[“Request Number”]) == Convert.ToString(this.Request.QueryString[“reqno”]))
{
foreach (string fileName in attachItem.Attachments)
{
if (fileName == fileUpload.FileName)
{
flag = true;
}
}
if (flag == true)
{
lblSuccess.Text = “File with same name already exists”;
}
else
{
SPSecurity.RunWithElevatedPrivileges(delegate()
{
attachItem.Attachments.Add(file.Name, AddFile(file));
attachItem.Update();
});
lblSuccess.Text = “File Uploaded Successfully”;
}
break;
}
}
}

internal static byte[] AddFile(FileInfo file)
{
FileStream fStream = File.OpenRead(file.FullName);
byte[] contents = new byte[fStream.Length];
fStream.Read(contents, 0, (int)fStream.Length);
fStream.Close();
return contents;
}