Read SharePoint Document Library File using CSOM

Read SharePoint Document Library File using CSOM

Please Visit My YouTube Channel for Technical Videos

Read SharePoint Document Library File using CSOM. In this post, you will Read SharePoint Document Library File using CSOM. SharePoint Document library is to upload any type of document and download it by CSOM. We can also access SharePoint Document Library by C# and Rest API etc. I also provide you code to upload a document in SharePoint Document Library.[AdSense-A]

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security;
using Microsoft.ProjectServer.Client;
using Microsoft.SharePoint.Client;
using PRCLNT = Microsoft.ProjectServer.Client;

namespace ReadDocumentFromDocumentLibrary_Using_CSOM
{
    class Program
    {

        static string UserName = "UserName";
        static string Passwords = "Password";
        public static string OnlinePWA = "PWAPath";
        static void Main(string[] args)
        {
            using (PRCLNT.ProjectContext ProjectCont = new PRCLNT.ProjectContext(OnlinePWA))//PWA Url
            {
                SecureString passWord3 = new SecureString();
                foreach (char c in Passwords.ToCharArray()) passWord3.AppendChar(c);
                ProjectCont.Credentials = new SharePointOnlineCredentials(UserName, passWord3);
                ProjectCont.Load(ProjectCont.Web);
                ProjectCont.ExecuteQuery();


                var list = ProjectCont.Web.Lists.GetByTitle("DocumentLib");
                var listItem = list.GetItemById(1);
                ProjectCont.Load(list);
                ProjectCont.Load(listItem, i => i.File);
                ProjectCont.ExecuteQuery();

                var fileRef = listItem.File.ServerRelativeUrl;
                var fileInfo = Microsoft.SharePoint.Client.File.OpenBinaryDirect(ProjectCont, fileRef);
                var fileName = Path.Combine("C:\\Users\\epmadmin\\Desktop\\YourFolderName", (string)listItem.File.Name);
                using (var fileStream = System.IO.File.Create(fileName))
                {
                    fileInfo.Stream.CopyTo(fileStream);
                }               
            }
        }
    }
}

 


Comments

  1. in the above code if path “C:\\Users\\epmadmin\\Desktop\\YourFolderName” is changed to “C:\\Users” then access is denied, I want to make sure that address work for every system as admin name will be different in each system

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

error: Content is protected !!