Upload a document to SharePoint Document Library using CSOM 2013
Hello Readers,
In this article, I wil share a piece of code to upload document into a document library using Client Side Object Model. Sharepoint is moving more towards Client Side Object model than Server side code for faster execution. As we move more towards next verison – SharePoint 2016, there is a heavy emphasis on Client side Code. This article talks about uploading a document into document library with the metadata values as well.
// Setting Client Context for the Upload operation
SP.ClientContext ctx = new SP.ClientContext(“http://mysite/site”);
Web web = ctx.Web;
FileCreationInformation newFile = new FileCreationInformation();
newFile.Content = System.IO.File.ReadAllBytes(@”C:\AccountInfo.doc”);
newFile.Url = “/” + fileName;
// Document Library Name
List docs = web.Lists.GetByTitle(“Employee Documents”);
Microsoft.SharePoint.Client.File uploadFile = docs.RootFolder.Files.Add(newFile);
context.Load(uploadFile);
context.ExecuteQuery();
SPClient.ListItem item = uploadFile.ListItemAllFields;
//Set the metadata for the newly uploaded file file
string docTitle = string.Empty;
item[“Title”] = docTitle ;
item[“Created by”] = “Sethu”;
item.Update();
context.ExecuteQuery();
Please read my next blogs to
Download a document from document library using CSOM.
Change Page layout of publishing pages in Sharepoint 2013 using powershell
Happy SharePointing 🙂