Upload A Document To A SharePoint 2013 Library Using Client Side Object Model

Introduction

In this article we explored how to upload a document from physical location to SharePoint Document library using client side object model. This can be achieved using server side or SharePoint Web Services.

Scenario

Many times there is a requirement to upload a document from a physical path to document library. We will explore it using Client Side Object model.

Before

before

Solution

  1. static void Main(string[] args)   
  2. {  
  3.   
  4.     try   
  5.     {  
  6.         // Starting with ClientContext, the constructor requires a URL to the server running SharePoint.   
  7.         using(ClientContext client = newClientContext("http://servername146/sites/test/"))  
  8.         {  
  9.             //client.Credentials = System.Net.CredentialCache.DefaultCredentials;  
  10.   
  11.             // Assume that the web site has a library named "FormLibrary".   
  12.             var formLib = client.Web.Lists.GetByTitle("Documents");  
  13.             client.Load(formLib.RootFolder);  
  14.             client.ExecuteQuery();  
  15.   
  16.             // FormTemplate path, The path should be on the local machine/server !  
  17.             string fileName = @ "C:\File.txt";  
  18.   
  19.             var fileUrl = "";  
  20.   
  21.             //Craete FormTemplate and save in the library.  
  22.             using(var fs = newFileStream(fileName, FileMode.Open))  
  23.             {  
  24.                 var fi = newFileInfo("test.txt"); //file Title  
  25.                 fileUrl = String.Format("{0}/{1}", formLib.RootFolder.ServerRelativeUrl, fi.Name);  
  26.                 Microsoft.SharePoint.Client.File.SaveBinaryDirect(client, fileUrl, fs, true);  
  27.                 client.ExecuteQuery();  
  28.             }  
  29.   
  30.             // Get library columns collection.  
  31.             var libFields = formLib.Fields;  
  32.             client.Load(libFields);  
  33.             client.ExecuteQuery();  
  34.   
  35.             Microsoft.SharePoint.Client.File newFile = client.Web.GetFileByServerRelativeUrl(fileUrl);  
  36.   
  37.             ListItem item = newFile.ListItemAllFields;  
  38.   
  39.             item["Title"] = "test";  
  40.             item.Update();  
  41.             client.ExecuteQuery();  
  42.         }  
  43.   
  44.     } catch (Exception ex)  
  45.     {  
  46.   
  47.     }  
  48.   
  49. }  
Final Output

output

Summary: The physical document is uploaded to the SharePoint document library.