Attaching a file to an item using code

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”;
attachItem.Attachments.Add(file.Name, AddFile(file));
lblSuccess.Text = “File Uploaded Successfully”;

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);
return contents;


One thought on “Attaching a file to an item using code

Add yours

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

Create a website or blog at

Up ↑

%d bloggers like this: