Upload a Document to a SharePoint 2013 Library Using Client Side Object Model

sharepoint 2013 upload document to document library.png

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. 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 (csom) in SharePoint 2013.

Read some SharePoint 2013 tutorials below:

Before:

sharepoint 2013 upload document to document library
sharepoint 2013 upload document to document library



Solution:
static void Main(string[] args)
{

try
{
// Starting with ClientContext, the constructor requires a URL to the server running SharePoint.
using(ClientContext client = newClientContext(“http://servername146/sites/test/”))
{
//client.Credentials = System.Net.CredentialCache.DefaultCredentials;

// Assume that the web site has a library named “FormLibrary”.
var formLib = client.Web.Lists.GetByTitle(“Documents”);
client.Load(formLib.RootFolder);
client.ExecuteQuery();

// FormTemplate path, The path should be on the local machine/server !
string fileName = @ “C:\File.txt”;

var fileUrl = “”;

//Craete FormTemplate and save in the library.
using(var fs = newFileStream(fileName, FileMode.Open))
{
var fi = newFileInfo(“test.txt”); //file Title
fileUrl = String.Format(“{0}/{1}”, formLib.RootFolder.ServerRelativeUrl, fi.Name);
Microsoft.SharePoint.Client.File.SaveBinaryDirect(client, fileUrl, fs, true);
client.ExecuteQuery();
}

// Get library columns collection.
var libFields = formLib.Fields;
client.Load(libFields);
client.ExecuteQuery();

Microsoft.SharePoint.Client.File newFile = client.Web.GetFileByServerRelativeUrl(fileUrl);

ListItem item = newFile.ListItemAllFields;

item[“Title”] = “test”;
item.Update();
client.ExecuteQuery();
}

} catch (Exception ex)
{

}

}


Final Output:

sharepoint 2013 upload document to document library csom
sharepoint 2013 upload document to document library csom

The physical document is uploaded to the SharePoint document library. Here we discussed how we can upload documents to document library using csom in SharePoint 2013.


You May Also like the Following SharePoint Online Tutorials:

About Sagar Pardeshi

I am Developer working on Microsoft Technologies for the past 6+years. I am very much passionate about programming and my core skills are SharePoint, ASP.NET & C#,Jquery,Javascript,REST. I am running this blog to share my experience & learning with the community I am an MCP, MCTS .NET & Sharepoint 2010, MCPD Sharepoint 2010, and MCSD HTML 5,Sharepoint 2013 Core Solutions. I am currently working on Sharepoint 2010, MOSS 2007, Sharepoint 2013,Sharepoint 2013 App Dev, C#, ASP.NET, and SQL Server 2008.

View all posts by Sagar Pardeshi →

Leave a Reply