How to upload documents to SharePoint 2013


SharePoint is a browser-based collaboration, content management, and extensible platform from Microsoft. The latest release of the product is SharePoint 2013.

In this article I will explain about one of the frameworks used for development in SharePoint 2013,   Client-side object model (CSOM). I am going to add a document through code to a SharePoint document library. I am going to use SharePoint object model to add document.

SharePoint 2013 provides a new client object model that enables you to create SharePoint solutions that run remotely from the SharePoint server farm. For example, the client object model enables you to consume and manipulate SharePoint data in Windows Forms applications, Windows Presentation Framework application, console applications, Silverlight applications, and ASP.NET Web applications.

The concept of development using the Client Object model was introduced in SharePoint 2010 and has been carried to the new versions. With the introduction of client-side object model, developers have the ability to perform core SharePoint functionality by using C# (managed client object model), JavaScript and Silverlight.

Creating a Sample Website

Now let's create a web form that illustrates the complete process in detail.

The prerequisites are that you have SharePoint 2013 and Visual Studio 2010 or 2013 installed in a development environment

Step1: Create a new ASP.Net web project, named SPUploadDocUsingCSOM

Step 2: Adding the Client Object Model references

    2.1 Right click the “References” node and choose “Add Reference”   

    2.2 Choose “Browse”                      

         2.2.1 Navigate to this folder: 
                C:\ Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI 

Note: this path might differ from your share point server version.

 3 Select these two files:

     3.1 Microsoft.SharePoint.Client.dll

     3.2 Microsoft.SharePoint.Client.Runtime.dll  

4 Make sure they are included in the references of your project:  

5 Add the following using-statement in your class:  

   using Microsoft.SharePoint.Client;



Step 3: The complete code of ShaePointUploader.aspx looks like this


<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="ShaePointUploader.aspx.cs" Inherits="SPUploadDocUsingCSOM.ShaePointUploader" %>































































































Here is the UI looks like at runtime:


Step 4: The complete code of ShaePointUploader.aspx.cs looks like this


using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

using Microsoft.SharePoint.Client;

using System.Net;

using System.IO;

using System.Text.RegularExpressions;

using System.Drawing;


namespace SPUploadDocUsingCSOM


    public partial class ShaePointUploader : System.Web.UI.Page


        protected void Page_Load(object sender, EventArgs e)



        public ClientContext SPClientContext { get; set; }

        public Web SPWeb { get; set; }

        public string SPErrorMsg { get; set; }

        protected void btnUpload_Click(object sender, EventArgs e)


            string sURL = txtSharePointURL.Text;

            string sDocName = string.Empty;

            if(!string.IsNullOrWhiteSpace(sURL) && !string.IsNullOrWhiteSpace(txtLibraryName.Text) && (FileLocalPath.HasFile))


                bool bbConnected = Connect(sURL, "UserName", "PassWord", "DomainName");

                if (bbConnected)


                    Uri uri = new Uri(sURL);

                    string sSPSiteRelativeURL = uri.AbsolutePath;

                    sDocName = UploadFile(FileLocalPath.FileContent, FileLocalPath.FileName, sSPSiteRelativeURL, txtLibraryName.Text);                 

  i                f(!string.IsNullOrWhiteSpace(sDocName))


                        lblMsg.Text = "The document " + sDocName + " has been uploaded successfully..";

                        lblMsg.ForeColor = Color.Blue;




                        lblMsg.Text = SPErrorMsg;

                        lblMsg.ForeColor = Color.Red;






        public bool Connect(string SPURL, string SPUserName, string SPPassWord, string SPDomainName)


            bool bConnected = false;



                SPClientContext = new ClientContext(SPURL);

                SPClientContext.Credentials = new NetworkCredential(SPUserName, SPPassWord, SPDomainName);

                SPWeb = SPClientContext.Web;



                bConnected = true;


            catch (Exception ex)


                bConnected = false;

                SPErrorMsg = ex.Message;


            return bConnected;



        public string UploadFile(Stream fs, string sFileName, string sSPSiteRelativeURL, string sLibraryName)


            string sDocName = string.Empty;



                if (SPWeb != null)


                    var sFileUrl = String.Format("{0}/{1}/{2}", sSPSiteRelativeURL, sLibraryName, sFileName);


                    Microsoft.SharePoint.Client.File.SaveBinaryDirect(SPClientContext, sFileUrl, fs, true);


                    sDocName = sFileName;



            catch (Exception ex)


                sDocName = string.Empty;

                SPErrorMsg = ex.Message;



            return sDocName;


Notice Connect and UploadFile I will explain each one in below sections.


Connecting to remote SharePoint site:

In order to connect to SharePoint remotely, we need to use the ClientContext class. It represents the context for SharePoint objects and operations. Use the ClientContext class to return context information about such objects as the current web application, site, site collection, or server version.

 SPClientContext = new ClientContext(SPURL); //SPURL is your share point site URL

We should create an instance of the ClientContext class and supply the authentication credentials through its Credentials property. 

SPClientContext.Credentials =new NetworkCredential(SPUserName, SPPassWord, SPDomainName);

Please specify the correct user name and password of your site otherwise an Unauthorized Exception will be thrown.

Retrieving the web’s properties using the load() method

var SPWeb = SPClientContext.Web;


ExecuteQuery() method executes the current request in the server and retrieves the data. In this case, it will connect to the SharePoint site and load the web site properties.



Uploading file to the SharePoint portal:

static SaveBinaryDirect() method of File object uploads the specified file to a SharePoint site without requiring an ExecuteQuery() method call. It sends raw binary across the wire and does not increase the message size.

File.SaveBinaryDirect(SPClientContext, sFileUrl, fs, true);


First Parameter requires a ClientContext object that represents the SharePoint site’s server context.


Second parameter expects a string that represents the server-relative URL of the file.


Third parameter is a Stream object that represents the file.


Last parameter is a Boolean value that specifies whether the file is overwritten if it already exists.



Client Object Model is a new feature available from SharePoint 2010. It provides features to program against a SharePoint site using .NET Managed Code. It provides client-side applications with access to a subset of the SharePoint Foundation server object model, including core objects such as site collections, sites, lists, and list items. The .NET managed client object model provides a larger subset of functionality for standalone client applications like windows form apps.





Understanding how to create and Install Windows Services in C#.Net

Windows Service in C#:This article is about how to create a Windows Service in C# .net using Visual ...

Read More >

Introduction to SharePoint and its features

This article will explore about the SharePoint introduction, its version and features.SharePoint is ...

Read More >

What are Frames? How to handle frames in Selenium WebDriver with C#?

IFrame (FullForm: Inline Frame) is an HTML document that is included in another HTML document and is...

Read More >

What is Synchronization? Handling Synchronization in Selenium WebDriver using C#:

Synchronization meaning: when two or more components involved to perform any action, we expect these...

Read More >

Sending Test reports by Email using Office 365, Gmail

Wouldn’t it be great if Test Report are sent automatically across team as soon the Test Execut...

Read More >

Token Based Authentication for Web API's

Securing ASP.NET Web API using Custom Token Based AuthenticationProviding a security to the Web API&...

Read More >

Extent Reports in Selenium CSharp (C#)

Reports play a fundamental role when it comes to TESTING. Tester can now  know the real-time r...

Read More >

How to Set Up Selenium WebDriver in Visual Studio Enterprise 2015?

Pre-requisite : Visual Studio Enterprise 2015 application should be installed into the system.Create...

Read More >

Custom Control in WPF

File Upload Custom Control in WPFThis article is about Custom control in WPF, Custom controls are al...

Read More >

ASP.NET: Audit Trail Implementation using Entity Framework

When you are working with certain projects which involves the Customer records, you might need to tr...

Read More >


Post a Comment

Try DevOpSmartBoard Ultimate complete Azure DevOps End-to end reporting tool

Sign Up

  • Recent
  • Popular
  • Tag
  • Key Metrics to Measure DevOps Success

    DevOps words means many things to many people and all the definitions might be partly right. DevOps is all about continuously seeking feedback, understanding challenges, and improving the way the soft...
  • Bulk Export Import Test Cases to Azure DevOps Test Plans using CSV file

    As a user of Azure DevOps Test Plans or TFS Test Management for manual testing, from a long time everyone including me had a wish, that copy of test cases from excel or csv file along with test steps ...
  • Azure DevOps Overview

    Now a days Azure DevOps is very famous with IT and Operations team along with developers, so what is Azure DevOps? It is a Software as a service (SaaS) platform from Microsoft that provides features r...
  • Volume Management in Kubernetes

    Since pods created in k8s are ephemeral, we are able to get the data as long as pods are alive, but if pods are terminated data stored in it completely lost and it cannot get back, for that we need to...
Monthly Archive

Contact Us
  • *
  • *