1

Task: There are some Excel files or documents on SharePoint site that I need to download to my local drive.

I'm a newbie to C#, so please give me directions on how to start and complete my task. I have VS 2012.

If someone has complete code then great. If not give me instructions for step #1, 2... and then I'll find or write my own code.

  • Are you using SharePoint 2010 or SharePoint 2013? – Jeff Freeman Jul 7 '14 at 15:01
  • 3
    Also, is there a reason you're doing this programmatically in C# (as opposed to doing it in PowerShell, or opening up the document library manually in explorer mode and copy/pasting the files)? – Jeff Freeman Jul 7 '14 at 15:08
  • I don't have Sharepoint but i do have VS 2012/2010 & 2008. I want to automate the process because we need to do this every month not just once. We need to automate this process. I don't have PowerShell or Sharepoint. Is this easy to do with Sharepoint 2010 or 2013 ?? – user1810575 Jul 7 '14 at 15:59
  • 1
    I meant, which version of SharePoint is the document library in? But, it sounds to me like you don't have access to the SharePoint servers, so you'll probably need to use the client side object model (CSOM) or REST services to download the files. @waqas-sarwar-mcse wrote more hints in his answer below – Jeff Freeman Jul 7 '14 at 16:12
1

check this post, this will give you couple of options to download the files from SharePoint. You can use the Rest, CSOM. Check the last reply on the post.

Here are couple of blogs, which will give you direction.

Programmatically download a SharePoint document library in .NET

http://www.c-sharpcorner.com/UploadFile/54db21/document-library-in-sharepoint-2010-programmatically-using-v/

2
using Microsoft.SharePoint;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace DownloadDoc
{
    class Program
    {
        void DownloadDocs()
        {



        }
        static void Main(string[] args)
        {
            string siteUrl = "siteUrl";

            using (SPSite site = new SPSite(siteUrl))
            {
                using (SPWeb web = site.OpenWeb())
                {
                    SPList docLib = web.Lists["library name"];
                    // loop through each item or document in the document library 

                    foreach (SPListItem item in docLib.Items)
                    {
                        // Access the file 
                        SPFile file = item.File;
                        if (file != null)
                        {

                            // retrieve the file as a byte array byte[] bArray = file.OpenBinary(); 
                            string filePath = Path.Combine("folder path", file.Name );
                            //open the file stream and write the file 
                            using (FileStream filestream = new FileStream(filePath, FileMode.Create, FileAccess.ReadWrite))
                            {
                                byte[] bArray = file.OpenBinary();
                                filestream.Write(bArray, 0, bArray.Length);
                                Console.WriteLine("Data Saved");
                            }
                        }
                    }
                }
            }
        }
    }

}
  • Can you please add some description about the code. – Asad Refai Jul 28 '15 at 9:41
0

The function below needs only the url path of a file in Sharepoint server, saves it at local directory and finally returns the file's path. It does not use the sharepoint client csom api. It also works with versions of a document, if you have enabled the versioning property of sharepoint document's library.


public string DownloadFile(string urlPath)
    {
        string serverTempdocPath = "";

        try
        {
            var request = (HttpWebRequest)WebRequest.Create(urlPath);
            var credentials = new NetworkCredential(configuration.Username, configuration.Password, configuration.Domain);
            string docExtension = urlPath.Split('.')[1];


            request.Credentials = credentials;
            request.Timeout = 20000;
            request.AllowWriteStreamBuffering = false;
            using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
            {
                using (Stream stream = response.GetResponseStream())
                {
                    serverTempdocPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), Guid.NewGuid() + "." + docExtension);

                    //Write to local disk
                    using (FileStream fs = new FileStream(serverTempdocPath, FileMode.Create))
                    {
                        byte[] read = new byte[256];
                        int count = stream.Read(read, 0, read.Length);
                        while (count > 0)
                        {
                            fs.Write(read, 0, count);
                            count = stream.Read(read, 0, read.Length);
                        }
                    }
                }
            }
        }
        catch (Exception exc)
        {
            Console.WriteLine(exc.Message);
            return "";
        }

        return serverTempdocPath;
    }
  • Did you test this before posting? – Taco_Buffet Aug 31 '16 at 20:01
  • The function above has been tested for not so big files. But it worked for me. – dsmyrnaios Sep 6 '16 at 7:47
0

Here is full CSOM Code to download your files

try
            {
                SecureString sec_strPassword = new SecureString();
                String Domain = "domain";
                using (ClientContext ctx = new ClientContext(QAPCOContext.DevURL))
                {
                    sec_strPassword = QAPCOContext.ConvertToSecureString("password");
                    NetworkCredential nc = new NetworkCredential("SPFarm", sec_strPassword, Domain);
                    ctx.Credentials = nc;
                    ctx.AuthenticationMode = ClientAuthenticationMode.Default;

                    List list = ctx.Web.Lists.GetByTitle("MIC GP Request");
                    ctx.Load(list);
                    var query = new CamlQuery() { ViewXml = "<View><Query><Where><Eq><FieldRef Name='Status' /><Value Type='Choice'>In progress</Value></Eq></Where></Query></View>" };
                    ListItemCollection items = list.GetItems(query);
                    ctx.Load(items);
                    ctx.ExecuteQuery();
                    Console.WriteLine("Total Count: " + items.Count);

                    foreach (var item in items)
                    {
                        var filePath = item["FileRef"];
                        Console.WriteLine("Path:" + "http://site/site" + filePath);

                        File file = item.File;
                        if (file != null)
                        {
                            //Loading Uploaded file
                            ctx.Load(file);
                            ctx.ExecuteQuery();


                            string dskFilePath = System.IO.Path.Combine(@"x:\temp\", file.Name);
                            using (System.IO.FileStream Local_stream = System.IO.File.Open(dskFilePath, System.IO.FileMode.CreateNew, System.IO.FileAccess.ReadWrite))
                            {
                                var fileInformation = File.OpenBinaryDirect(ctx, file.ServerRelativeUrl);
                                var Sp_Stream = fileInformation.Stream;
                                //open the file stream and write the file 
                                Sp_Stream.CopyTo(Local_stream);
                            }

                        }
                    }


                    Console.ReadKey();


                }
            }
            catch (Exception ex)
            {
                //
                Console.WriteLine(ex.Message);
                Console.ReadKey();
            }

`

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.