Programmatically get the list of excel files by authenticating from SharePoint URL move that files to Local path in C#?

santhosh reddy 21 Reputation points
2020-12-26T08:52:49.547+00:00

Authenticate the SharePoint URL with UserName, Password(Without using MFA) using c# code and Get the list of files from that SharePoint URL and move those files to the Local path of the computer?

C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,358 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Timon Yang-MSFT 9,576 Reputation points
    2020-12-28T08:23:02.1+00:00

    Please install a nuget package first: Microsoft.SharePointOnline.CSOM.
    Then try the following code:

            static void Main(string[] args)  
            {  
                using (ClientContext ctx = new ClientContext("https://tenantname.sharepoint.com/sites/sitename/"))  
                {  
                    string account = "";  
                    string password = "********";  
                    var secret = new SecureString();  
                    foreach (char c in password)  
                    {  
                        secret.AppendChar(c);  
                    }  
                    ctx.Credentials = new SharePointOnlineCredentials(account, secret);  
                    ctx.Load(ctx.Web);  
                    ctx.ExecuteQuery();  
      
                    List list = ctx.Web.Lists.GetByTitle("Documents");  
      
                    FileCollection files = list.RootFolder.Folders.GetByUrl("/sites/sitename/shared documents/foldername").Files;  
      
                    ctx.Load(files);  
                    ctx.ExecuteQuery();  
      
                    foreach (Microsoft.SharePoint.Client.File file in files)  
                    {  
                        FileInformation fileinfo = Microsoft.SharePoint.Client.File.OpenBinaryDirect(ctx, file.ServerRelativeUrl);  
      
                        ctx.ExecuteQuery();  
      
                        using (FileStream filestream = new FileStream("C:" + "\\" + file.Name, FileMode.Create))  
                        {  
                            fileinfo.Stream.CopyTo(filestream);  
                        }  
      
                    }  
                };  
      
            }  
    

    If the response is helpful, please click "Accept Answer" and upvote it.
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments