Upload file to Sharepoint using client object model

04/02/2013 00:53

First add references to 'Microsoft.SharePoint.Client' and 'Microsoft.SharePoint.Client.Runtime' dll's. You can find them in 14\ISAPI folder if not in GAC.

Help reference from: https://blogs.msdn.com/b/sridhara/archive/2010/03/12/uploading-files-using-client-object-model-in-sharepoint-2010.aspx

 

using System;
using System.Linq;
using System.Collections.Generic;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Client;
using System.Net;

namespace UploadFileToSharePoint
{
    class Program
    {
        static void Main(string[] args)
        {
                string webUrl = "https://server/siteCollection";
                string folderUrl = "Shared%20Documents/MyF older/My Subfolder";
                string sourceFolder = "c:/";
                string fileName = "y.zip";

                try
                {
                    using (ClientContext context = new ClientContext(webUrl))
                    {
                        Web web = context.Web;
                        context.Load(web);
                        context.Credentials = new NetworkCredential("username", "P@ssw0rd", "domain");
                        Folder folder = context.Web.GetFolderByServerRelativeUrl(folderUrl);
                        context.Load(folder);
                        context.Load(folder.Files);
                        context.ExecuteQuery();
                        Console.WriteLine("Web Url: {0}", web.Title);
                        Console.WriteLine("Folder Name: {0}", folder.Name);
                        foreach (File file in folder.Files)
                        {
                            Console.WriteLine("File: {0}", file.Name);
                        }

                        FileCreationInformation newFile = new FileCreationInformation();
                        newFile.Content = System.IO.File.ReadAllBytes(sourceFolder + fileName);
                        newFile.Url = fileName;
                        Microsoft.SharePoint.Client.File uploadFile = folder.Files.Add(newFile);
                        context.Load(uploadFile);
                        context.ExecuteQuery();
                        Console.WriteLine("{0} file uploaded to: {1}", fileName, folderUrl);
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
                finally
                {
                   
                    Console.Read();
                }
               
           
        }

    }
}