Tuesday, May 12, 2009

How to programmatically attach a document or file in a SPListItem

How to programmatically attach a document or file in a SPListItem

In this post I discussed, how we can programmatically attach a document or file in a SPListItem of SPList (SharePoint's List).

Following method contains the logic to attach the document / file (codes with comments are self-explainatory).



/// <summary>
/// Programmatically Attach document in SPDocument Library
/// </summary>
void documentAttachmentInSPList()
{
//SPListItem spListItem = null; //write code to get the SPListItem.
//fileUpload is control ID of ASP.Net FileUpload control
if (!string.IsNullOrEmpty(fileUpload.FileName))
{
//Get file extension ( *.doc OR *.docx )
string fileExtension
= fileUpload.FileName.Substring(fileUpload.FileName.IndexOf("."));

//FILENAME is file name visible in SPListItem
//Check file is already added or not. If added then delete it.
for (int i = 0; i < spListItem.Attachments.Count; i++)
{
if ((spListItem.Attachments[i] != null)
&& (spListItem.Attachments[i].Equals("FILENAME" + fileExtension)))
{
spListItem.Attachments.Delete("FILENAME" + fileExtension);
break;
}
}

//Attach the file.
spListItem.Attachments.Add("FILENAME" + fileExtension, fileUpload.FileBytes);

//LISTNAME is SPList's name
//See the attached file as link in user-created custom column.
string attachmentURL = Request.Url.Scheme + "://" + Request.Url.Authority
+ "/Lists/" + "LISTNAME" + "/Attachments/" + spListItem.ID + "/";

spListItem["Attached File"]
= attachmentURL + "FILENAME" + fileExtension + ", View FILE";
}
}

5 comments:

Unknown said...

You cannot use Attachments property for an item in Document Library. Hence above code doesn't work.

Is there any other way to do this?

Avinash said...

Hi Praveen,

Yes, you are right. Current post is only for SPList.

For SPDocumentLibrary please refer following post:
How to programmatically upload a document in a SPDocumentLibrary


~ Avinash

Anonymous said...

can anybody tell me what Rquest mean in this code please

Unknown said...

Request (not Rquest) means --

this.Page.Request
OR
HttpContext.Current.Request

~ Avi

Unknown said...

Sorry for my ignoracne but where do i paste this code? I have created a custom site page and need a field to attach docs.

Google