Friday, June 27, 2014

Adding attachment to list programmatically in SharePoint 2010 OR Adding list item to SharePoint 2010

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using Microsoft.SharePoint;

namespace ListFileUpload
{
    class Program
    {
        static void Main(string[] args)
        {
            FileUploadToList();
        }



        public static void FileUploadToList()
        {
            //file location which needs to be uploaded
            FileStream stream = File.OpenRead(@"C:\Users\jinivthakkar\Desktop\UploadToListAsAttachment.docx");
            string path = @" C:\Users\jinivthakkar\Desktop\UploadToListAsAttachment.docx ";

            //extract file name
            string fileName = Path.GetFileName(path);

            //extract extension
            string extension = System.IO.Path.GetExtension(path);

            //extract Title
            string docTitle = fileName.Substring(0, fileName.Length - extension.Length);


            //Read file and copy information in byte array
            byte[] fileBytes = new byte[stream.Length];
            stream.Read(fileBytes, 0, fileBytes.Length);

            //Site url where document which needs to be uploaded
            using (SPSite oSPsite1 = new SPSite("http://myserver01:8585/sites/Test"))
            {

                using (SPWeb oSPWeb = oSPsite1.OpenWeb())
                {
                    oSPWeb.AllowUnsafeUpdates = true;
                    //List where file needs to be uploaded
                    SPList myList = oSPWeb.Lists["MyList"];

                    SPListItem item = myList.Items.Add();
                    item["Title"] = docTitle;
                    item.Update();
                    SPAttachmentCollection attachments = item.Attachments;
                    int docID = item.ID;
                    attachments.Add(fileName, fileBytes);

                     //Item update,list update
                    item.Update();
                    myList.Update();
                    stream.Close();

                }
            }
        }

    }
}


This code reads a file on local machine and adds list item as attachment to list in SharePoint 2010

No comments:

Post a Comment