C# CSOM How to Upload Document into SharePoint Online Document Library

In this article we will see how to upload document into SharePoint Online Document Library using

SharePoint Client Object Model CSOM. Also I have given piece of code to get document ID of the 

uploaded document.

Here is the code:

            string siteUrl = "https://domainname.sharepoint.com/sites/contoso5/";

            string docUrl = "https://domainname.sharepoint.com/sites/contoso5/DocLib/MyFolder/NewPDF.pdf";

            string pathToFile = @"C:\NewPDF.pdf";

            var clientContext = GetClientContext(siteUrl);

            Web web = clientContext.Web;

            clientContext.Load(web, a => a.ServerRelativeUrl);

            clientContext.ExecuteQuery();

            List documentsList = clientContext.Web.Lists.GetByTitle("DocLib");

            var fileCreationInfo = new FileCreationInformation();

            fileCreationInfo.Content = System.IO.File.ReadAllBytes(pathToFile);

            fileCreationInfo.Overwrite = true;

            fileCreationInfo.Url = docUrl;

            Microsoft.SharePoint.Client.File uploadFile = documentsList.RootFolder.Files.Add(fileCreationInfo);

            uploadFile.ListItemAllFields["Title"] = "File Uploaded Through CSOM";

            uploadFile.ListItemAllFields.Update();

            clientContext.ExecuteQuery();

In case, if you want to get the document ID of the uploaded document, you can get by adding below line of code before the clientContext.ExecuteQuery();

var id = uploadFile.ListItemAllFields.Id;


Happy PC (Programming / Configuring)

Comments

Popular posts from this blog

In C# CSOM How to Delete Folders Recursively, Sub-Folders, Files in SharePoint Online Document Library

How Get, Set, Delete Permission on SharePoint Online Site using Graph API

What is SharePoint online default authentication method? And which credential flow it is using to authenticate?