Friday 11 September 2015

Client Object Model Code to Upload a File /CSOM File Upload

Below is the Client object Model code to upload file using CSOM. Here i am using Console Application and hard coding the path of file ofcourse you can create an windows form with user input to read the path, in the below case i am using console model .

Since i am uploading file to different domain so i am passing my credentials ("Username","PassWord","DomainName"); and I am uploading to Document Library Named Documents.


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)
        {
            string url = "http://SP2013.dev.com/";

            ClientContext ctx = new ClientContext(url);
            try
            {
                ctx.Credentials = new NetworkCredential("fasx669", "Wintertime123", "world");
            }
            catch(Exception ex)
            {
                Console.WriteLine(ex.Message);
                Console.ReadKey();
             
           
            }
            try
            {
                FileCreationInformation file1 = new FileCreationInformation();
                file1.Url = "SoreddyManjunath.txt";
                file1.Content = System.IO.File.ReadAllBytes(@"C:\MSFile-Manju.txt");
                List doclib = ctx.Web.Lists.GetByTitle("Documents");
                Microsoft.SharePoint.Client.File myfile = doclib.RootFolder.Files.Add(file1);
                ctx.Load(myfile);
                ctx.ExecuteQuery();
                ListItem item = myfile.ListItemAllFields;
                item["Title"] = "Welcometo File upload";
                item.Update();
                ctx.Load(item);
                ctx.ExecuteQuery();
                Console.WriteLine("File uploaded Succesfully");
                Console.ReadKey();
            }
            catch(Exception ex)
            {
                Console.WriteLine(ex.Message);
                Console.ReadKey();
            }

        }
    }
}



Output:






No comments:

Post a Comment