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

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)
- {
- }
- }

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

Akash KumharPosted Oct 31, 2018, 3:40 AM
Thanks for sharing...
Vero Gro MPosted Oct 9, 2018, 12:06 PM
Hi, I have sso in my sharepoint site, and I implemented SharePointOnlineCredentials, my credentials were accepted but I get (401) Unauthorized. Any suggestions?
vivek rmPosted May 7, 2018, 11:05 PM
If i run same code for Office365 site , i am getting below error - The remote server returned an error: (401) Unauthorized. any idea why this is so ??
Rupali ShindePosted Feb 4, 2016, 3:19 AM
if i run same code for Office365 site , i am getting below error - The remote server returned an error: (401) Unauthorized. any idea why this is so ??
Rupali ShindePosted Feb 4, 2016, 1:12 AM
can you please upload source file of it ??
Ankit SaxenaPosted Feb 3, 2016, 12:28 PM
Thanks for sharing. Usefull info.
Nanddeep NachanPosted Jan 30, 2016, 8:47 AM
Nice share
Santhakumar MunuswamyPosted Jan 29, 2016, 2:08 AM
Thanks for nice share
Madan BhintadePosted Jan 28, 2016, 2:26 PM
Nice!