2010年12月17日 星期五

Save Attachment

I don't know if this is work but just for reference.

///
/// Programmatically Attach document in SPDocument Library
///

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";
}
}