dayanrr91 dayanrr91 - 2 months ago 14
C# Question

Download a file from sharepoint

I am trying to download a file from sharepoint, I have this code and throw error code 500.

static void DownloadFile(){
string serverFilePath = "Here goes my URL, that open the file from any tab";
var password = new SecureString();
foreach (char c in Configuration.password) {
password.AppendChar(c);
}
// theese are the credentials and work fine because I tested in another method
var o365credentials = new SharePointOnlineCredentials(Configuration.userName, password);

var url = string.Format("{0}/{1}", Configuration.siteUrl, serverFilePath);
// My destination folder
string destPath = @"C:\publisher";
var request = System.Net.HttpWebRequest.Create(url);
request.Credentials = o365credentials;
using (var sReader = new StreamReader(request.GetResponse().GetResponseStream())) {
using (var sWriter = new StreamWriter(destPath)) {
sWriter.Write(sReader.ReadToEnd());
}
}
}

Answer

you can achieve this task using WebRequest in order to download files from sharepoint site:

public void DownloadFile(string serverFilePath, string destPath)
        {
            var url = string.Format("{0}/{1}", ServerURL, serverFilePath);
            createDirectiory(Path.GetDirectoryName(destPath)); // this method creates your directory
            var request = System.Net.HttpWebRequest.Create(url);
            request.Credentials = System.Net.CredentialCache.DefaultCredentials;
            using (var sReader = new StreamReader(request.GetResponse().GetResponseStream()))
            {
                using (var sWriter = new StreamWriter(destPath))
                {
                    sWriter.Write(sReader.ReadToEnd());
                }
            }
        }

if you wish to use the Client-object-model you read that: How to get a file using SharePoint Client Object Model with only an absolute url at hand?

Comments