Sunday, 14 April 2013

Attachment to Sharepoint List item from FileUpload Control in Custom WP

private void UploadFileToSharepointListItem(FileUpload flUpldCntrlID, string strFilePrefix)
        {
            //Check the FileUpload control has the file

            if (flUpldCntrlID.PostedFile != null && !string.IsNullOrEmpty(flUpldCntrlID.FileName))
            {
                int ItemID = Convert.ToInt32(Request.QueryString["ItemID"].ToString().Trim());
                SPWeb web = SPContext.Current.Web;
                SPList NewCountryList = web.Lists["ListName"];   // list name
                SPListItem item = NewCountryList.GetItemById(ItemID);
             
                //Read the Contents from the file in Local machine
                Stream fs = flUpldCntrlID.PostedFile.InputStream;
                byte[] fileContents = new byte[fs.Length];
                fs.Read(fileContents, 0, (int)fs.Length);
                fs.Close();

                // Add the file to the ListItem as an Attachment
                SPAttachmentCollection attachments = item.Attachments;
                string fileName = strFilePrefix + Path.GetFileName(flUpldCntrlID.PostedFile.FileName);
                attachments.Add(fileName, fileContents);
                item.Update();              
            }
        }

No comments:

Post a Comment