Monday, 18 July 2016

AddAttachment CSOM SharePoint 2010

AddAttachment to Sharepoint 2010 List item CSOM


Below is the code  to add an attachment to sharePoint 2010 list item through CSOM with WebReference, 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.SharePoint.Client;
using System.IO;
using System.Data;
using System.Net;

namespace CSOMFileUpload
{
    class Program
    {
        static void Main(string[] args)
        {
           
            const string listName = "Test";                   
            var credentials = new NetworkCredential("manjunath.soreddy", "MS", "dev");
            var clientContext = new ClientContext("https://spdev.com/TestSite/");
            clientContext.Credentials = credentials;
            var list = clientContext.Web.Lists.GetByTitle(listName);
            var itemCreateInfo = new ListItemCreationInformation();
            var newItem = list.AddItem(itemCreateInfo);
            newItem["Title"] = "Soreddy Client API";
            newItem.Update();
            clientContext.ExecuteQuery();
            clientContext.Load(newItem);
            clientContext.ExecuteQuery();          
            string path = @"c:\OutPutLog.txt";
           
//Here Uploadfile.inv is a Webreference which we have added to SharePoint 2010 Site from Visual Studio to add follow below steps
// Solution Explorer---> Add Service Reference ---> Advanced-> Add Web Reference --> URL

           var refin = new Uploadfile.inv.Lists();
           refin.Credentials = CredentialCache.DefaultCredentials;
           refin.Url = "https://spdev.com/TestSite/");
/_vti_bin/Lists.asmx";
           refin.AddAttachment(listName, newItem["ID"].ToString(), Path.GetFileName(path),
                                      System.IO.File.ReadAllBytes(path));
        }
    }
}



OutPut:





No comments:

Post a Comment