Lit Item Attachments in SharePoint
A list item in SharePoint can have multiple attachments. Below is a code snippet in c#.Net to add an attachment to a list item programmatically.
|
This example demonstrates how a file, uploaded through a file upload control is added as an attachment to a list item.
using (SPSite oSPsite = new SPSite(http: //website Url/))
{
using (SPWeb oSPWeb = oSPsite.OpenWeb())
{
oSPWeb.AllowUnsafeUpdates = true;
// Fetch the List
SPList list = oSPWeb.Lists["MyList"];
// Get the List item
SPListItem listItem = list.GetItemById(1);
// Get the Attachment collection
SPAttachmentCollection attachmentCollection = listItem.Attachments;
Stream attachmentStream;
Byte[] attachmentContent;
// Get the file from the file upload control
if (this.fileDocAttach.HasFile)
{
attachmentStream = this.fileDocAttach.PostedFile.InputStream;
attachmentContent = new Byte[attachmentStream.Length];
attachmentStream.Read(attachmentContent, 0, (int)attachmentStream.Length);
attachmentStream.Close();
attachmentStream.Dispose();
// Add the file to the attachment collection
attachmentCollection.Add(this.fileDocAttach.FileName, attachmentContent);
}
// Update th list item
listItem.Update();
oSPWeb.AllowUnsafeUpdates = false;
}
} |
No comments:
Post a Comment