Download file from Sharepoint Online using C#.net?

11,365

Solution 1

Following C# program works for downloading files from SharePoint

Using NuGet Packet Manager, install Microsoft.SharePointOnline.CSOM

This package contains SharePoint and Client Object Model libraries

C# Code

using Microsoft.SharePoint.Client;
using System;
using System.IO;
using System.Linq;
using System.Security;

namespace SharePointFileDownlaload
{
    class Program
    {
        static void Main(string[] args)
        {
            string UserName = String.Empty;
            Console.Write("Type username and press enter: ");
            UserName = Console.ReadLine();

            string Pwd = String.Empty;
            Console.Write("Type password and press enter: ");
            Pwd = Console.ReadLine();

            string drive = String.Empty;
            Console.Write("Type the computer drive where you want to store the file and press enter: ");
            drive = Console.ReadLine();

            Console.WriteLine("Process started .... ");
           
            try
            {
                DownloadFilesFromSharePoint("MyFolder", UserName, Pwd, drive);
            }
            catch(Exception ex)
            {
                Console.WriteLine("ERROR: "+ex.Message);
            }

            Console.ReadLine();
        }

        private static void DownloadFilesFromSharePoint(string folderName, string UserName, string Pwd, string driveName)
        {
            //Load Libraries from SharePoint
            ClientContext ctxSite = GetSPOContext(UserName, Pwd);
            ctxSite.Load(ctxSite.Web.Lists);
            ctxSite.ExecuteQuery();

            Web web = ctxSite.Web;
            var docLibs = ctxSite.LoadQuery(web.Lists.Where(l => l.BaseTemplate == 101));  //DocumentLibrary only
            ctxSite.ExecuteQuery();

            foreach (var list in docLibs)
            {
                //Console.WriteLine(list.Title);
                ctxSite.Load(list.RootFolder.Folders);
                ctxSite.ExecuteQuery();

                string listTitle = list.Title;
                

                //Console.WriteLine("List Tile ------------------------------- " + listTitle);
                foreach (Folder folder in list.RootFolder.Folders)
                {
                    ctxSite.Load(folder.Files);
                    ctxSite.ExecuteQuery();

                    if (String.Equals(folder.Name, folderName, StringComparison.OrdinalIgnoreCase))
                    {
                        var folderDestination = driveName+@":\Test\SharePoint\" + listTitle + @"\" + folderName + @"\";
                        ctxSite.Load(folder.Files);
                        ctxSite.ExecuteQuery();

                        foreach (var file in folder.Files)
                        {
                            var fileName = Path.Combine(folderDestination, file.Name);
                            if (!System.IO.File.Exists(fileName))
                            {
                                Directory.CreateDirectory(folderDestination);
                                var fileRef = file.ServerRelativeUrl;
                                var fileInfo = Microsoft.SharePoint.Client.File.OpenBinaryDirect(ctxSite, fileRef);
                                using (var fileStream = System.IO.File.Create(fileName))
                                {
                                    fileInfo.Stream.CopyTo(fileStream);
                                }
                            }
                        }
                        Console.WriteLine("Downloaded the file in " + folderDestination);
                    }

                }
                
            }
            
        }

        private static ClientContext GetSPOContext(string UserName, string Pwd)
        {
            
            string spsiteurl = "https://company.sharepoint.com/sites/YourSite/";  
            
            var secure = new SecureString();
            foreach (char c in Pwd)
            {
                secure.AppendChar(c);
            }
            ClientContext spoContext = new ClientContext(spsiteurl);
            spoContext.Credentials = new SharePointOnlineCredentials(UserName, secure);
            return spoContext;

        }

        private static void GetAllItemNamesInSP(string UserName, string Pwd)
        {
            //Load Libraries from SharePoint
            ClientContext ctxSite = GetSPOContext(UserName, Pwd);
            ctxSite.Load(ctxSite.Web.Lists);
            ctxSite.ExecuteQuery();

            foreach (List list in ctxSite.Web.Lists)
            {
                string nameTest = list.Title;
                string testVal = list.BaseType.ToString();
                Console.WriteLine(nameTest + " -------------- " + testVal);
                if (list.BaseType.ToString() == "DocumentLibrary")
                {
                }

            }
            Console.ReadLine();
        }

    }
}

Solution 2

Try the code snippet below, download file from Library to Local using SharePoint Online CSOM:

using Microsoft.SharePoint.Client;
using System.IO;
using System.Linq;
using System.Security;

namespace CSOM
{
    class Program
    {
        static void Main(string[] args)
        {

            using (ClientContext ctx = new ClientContext("https://tenantname.sharepoint.com/sites/sitename/"))
            {
                string password = "********";
                string account = "[email protected]";
                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("libraryTitle");

                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);
                    }

                }
            };

        }


    }
}
Share:
11,365

Related videos on Youtube

H P
Author by

H P

Updated on June 04, 2022

Comments

  • H P
    H P almost 2 years

    I wanted to download the file\files from SharePoint online to my local and I am struggling with the code samples. I searched on google but didn't get any valuable information.

  • H P
    H P about 3 years
    Thank you, everyone! I really appreciate your all help :)
  • David Ford
    David Ford almost 3 years
    This uses the now-deprecated SharePointOnlineCredentials and is not available for .NET core. It is also a .NET Framework (now a dead product) app
  • David Ford
    David Ford almost 3 years
    As below: SharePointOnlineCredentials is deprecated. The code above is .NET Framework, now a dead product.
  • Jerry
    Jerry almost 3 years
    @DavidFord , Hey Guy, Look at the question, it's posted on 2019 and in 2019, there is no .NET Core CSOM Library released !!!!!!!!
  • David Ford
    David Ford almost 3 years
    @Jerry - Microsoft have stated very clearly that .NET Framework 4.8 is the last version of .NET Framework that will be published. This announcement was made years ago by my recollection. It will be supported for quite some time but is at end of life. .NET Framework 4.8 was released 2 years ago (in 2021). Feel free to provide evidence that a .NET Framework 4.9 will ever be released and that I'm incorrect.
  • Jake Smith
    Jake Smith almost 3 years
    .NET 5 has been released. There is no more .NET Framework other than long term support for 4.8 as far as I understand it. But dotnet core 3.1 is long term support as well. Question is, how to talk to SharePoint when you are using .NET 5 or dotnet core 3.1 for those that are not using the deprecated .NET Framework?
  • Jake Smith
    Jake Smith almost 3 years
    I believe you can just use System.Net.NetworkCredential instead of SharePointOnlineCredentials. I'm in the middle of trying to get this to work. If I do, I'll let you know
  • Jake Smith
    Jake Smith almost 3 years
    Not having a lot of luck. Sounds like the dotnet core library has removed username/password authentication as an option in general: docs.microsoft.com/en-us/sharepoint/dev/sp-add-ins/…
  • Jerry
    Jerry almost 3 years
    @DavidFord , I know in 2021 you are correct, but the original question was posted in 2019 right ? And my answer was also posted in 2019, so I'm also correct in 2019, right ? As .NET Core CSOM Library was released in 2020/6/23 developer.microsoft.com/en-us/office/blogs/… There was nothing except .NET Framework CSOM in 2019.
  • Jerry
    Jerry almost 3 years
    @JakeSmith, this won't be the Question, Microsoft published the official document about how to use CSOM in .NET Core Solution : docs.microsoft.com/en-us/sharepoint/dev/sp-add-ins/…
  • David Ford
    David Ford almost 3 years
    @Jerry - using your same logic, when I added my comment in 2021 I was entirely valid. Note that Stack Overflow isn't about "is this question and answer correct in the time it was written, 2019" - it's about helping developers now to solve problems. Highlighting that your answer was correct in 2019 isn't useful to a developer today. Providing a note as I did to current developers that this isn't the correct solution 2021 is useful. Even more useful would be an edited answer (from you) that also points to the updated process for .NET core.
  • David Ford
    David Ford almost 3 years
    Primarily my answer was aiming to help developers from not going down an end-of-life path of development. I'm hoping that is both clear and useful to people.
  • Jerry
    Jerry almost 3 years
    @DavidFord, Microsoft have published the official document last year: docs.microsoft.com/en-us/sharepoint/dev/sp-add-ins/…, If Developer has Googled with keyword, it's easy to find out.