Prasad Bolla's SharePoint Blog

Click Here to go through the Interesting posts within my Blog.

Click Here to go through the new posts in my blog.

Tuesday, February 12, 2013

Adding attachment to an SharePoint ListItem while Insertion



SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                SPListItemCollection myColl = SPContext.Current.Web.Lists["List Attachments Test"].Items;
                SPListItem item = myColl.Add();
                item["Title"] = txtTitle.Text;
                item.Update();
                //strItemID=item.ID.ToString();

                SPListItem currentItem = SPContext.Current.Web.Lists["List Attachments Test"].GetItemById(item.ID);
                byte[] contents = null;
                if (fuBrowse.PostedFile != null && fuBrowse.HasFile)
                {
                    using (Stream fileStream = fuBrowse.PostedFile.InputStream)
                    {
                        contents = new byte[fileStream.Length];
                        fileStream.Read(contents, 0, (int)fileStream.Length);
                        fileStream.Close();
                    }
                    SPAttachmentCollection attachments = currentItem.Attachments;
                    string fileName = Path.GetFileName(fuBrowse.PostedFile.FileName);
                    attachments.Add(fileName, contents);
                    currentItem.Update();
                }
            });

No comments:

Post a Comment