Cannot copy Excel files from SharePoint Doc library to local machine using C#

I am developing a C# console app that needs to copy an xlsx file from a SharePoint doc library to the local disk.

This runs as a scheduled task with specific user credentials defined for the task.

I have tried:

Mapping a network drive and using System.IO.File.Copy. This works as along as the drive stays mapped however the drive mapping keeps failing because SharePoint starts denying access. This is due to the login expiring and SharePoint requiring a login to refresh the credentials. I would prefer this solution if anyone has advice however it looks like this is a known issue for SharePoint online and mapping drives.

Using the WebClient I tried both the DownloadFile and DownloadData methods. Using either method I can successfully contact the SharePoint server and get to the file. It acts like it downloads and returns no errors however it only downloads a portion of the file (around 45KB and the file is ~200KB). I cannot get it to download the entire file.

I have been reading many posts across many forums for the past two days and have seen others with this problem but many of the posts are quite old. I have seen a number of posts that say using DownloadFile should solve the problem. Based on a couple postings I found people do have problems with Office (Word and Excel) files getting corrupted but I am not finding definite solutions. Also, I am new to this so I am assuming there is something I am overlooking. I can't believe it is this hard to copy a single file. 

Here is the WebClient code I am using:

string url = ConfigurationManager.AppSettings["SharePointLocation"];

// Create a new WebClient instance.
WebClient myClient = new WebClient();

myClient.UseDefaultCredentials = true;
myClient.Headers.Add("user-agent", "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.94 Safari/537.36");

// Download the Web resource and save it into the current filesystem folder.
myClient.DownloadFile(url, ConfigurationManager.AppSettings["MasterScheduleLocalPath"]);

Any pointers would be much appreciated. This has turned what I thought was a quick fix into a big problem.

Thanks,

DMK

June 20th, 2015 8:41pm

Hi,

Can you please share the url you are trying for the file? It may happen like the url has querystrings that might represent not the actual file.

Free Windows Admin Tool Kit Click here and download it now
June 22nd, 2015 1:29am

Hi,

Please fetch the Excel file from Document Library as File.

 Microsoft.SharePoint.Client.File file = listItem.File;
                    file.CheckOut();

                        ClientResult<Stream> data = file.OpenBinaryStream();

                        //Load the Stream data for the file
                        clientContext.Load(file);
                        clientContext.ExecuteQuery();

                        //If data received, upload to Local storage
                        if (data != null)
                        {
                            using (var memory = new MemoryStream())
                            {
                                byte[] buffer = new byte[1024 * 64];
                                int nread = 0;

                                while ((nread = data.Value.Read(buffer, 0, buffer.Length)) > 0)
                                {
                                    memory.Write(buffer, 0, nread);
                                }
                                memory.Seek(0, SeekOrigin.Begin);
                                var fileName = Path.Combine(@"D:\", listItem.File.Name);
                                using (var fileStream = System.IO.File.Create(fileName))
                                {
                                    memory.CopyTo(fileStream);
                                }
                            }
                        }

The above code puts your excel file in D drive.

Thanks.

June 22nd, 2015 2:24pm

Thank you both for your suggestions.

Sohel, I thought about that and tried many different permutations of the URL. Unfortunately it is an internal website on my company's network so I cannot post the URL here. Based on monitoring the errors returned with each try I think I have the proper URL.

A'Kumar,  I will give your suggestion a try. I realize as I am looking at this I did not try a binary stream with the SharePoint client, only the WebClient. 

It will likely be a couple days before I can try this (I am on another task right now). I will post an update once I get a chance to test it.

Thank you both for the suggestions!

DMK

Free Windows Admin Tool Kit Click here and download it now
June 24th, 2015 5:44pm

Hi,

Any update?

Best Regards

June 28th, 2015 11:01pm

This topic is archived. No further replies will be accepted.

Other recent topics Other recent topics