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

C# Http Method How to Upload Document into SharePoint Online Document Library

Doc Chat Studio: Building a Production-Grade RAG AI with LangChain, FAISS & Streamlit

C# How to Call Graph API from Web API using MSAL Authentication