To be able to download file from SharePoint Online/Office 365 using CSOM or REST the authentication has to be performed.
About SharePoint Online authentication
Since SharePoint Online (SPO) uses claims based authentication, you could consider the following options:
Consume SharePoint REST service using .NET
In order to consume SharePoint REST service using .NET you could consider the following approaches:
- HttpClient - Provides a base class for sending HTTP requests and receiving HTTP responses from a resource identified by a URI. (
.NET Framework 4.5) - WebClient - provides common methods for sending data to and receiving data from a resource identified by a URI. (
.NET Framework 1.1) - HttpWebRequest - provides an HTTP-specific implementation of the WebRequest class, more low-level then the previous ones (
.NET Framework 1.1)
All of them allows to download a file from SharePoint Online.
Examples
Example 1. How to specify SPO credentials using SharePointOnlineCredentials class
var request = (HttpWebRequest)WebRequest.Create(endpointUri); request.Credentials = new SharePointOnlineCredentials(username, securedPassword); //...
Example 2. How to specify SPO authentication cookies using MsOnlineClaimsHelper class:
var claimshelper = new MsOnlineClaimsHelper(webUri, userName, password); var endpointUri = new Uri(webUri,string.Format("/_api/web/getfilebyserverrelativeurl('{0}')/$value", fileUrl)); var request = (HttpWebRequest)WebRequest.Create(endpointUri); request.Headers.Add("X-FORMS_BASED_AUTH_ACCEPTED", "f"); request.Method = "GET"; request.CookieContainer = claimshelper.CookieContainer; //...
Key points:
- SharePoint Auth cookies are passed via
CookieContainer property - According to Files and folders REST API reference the following endpoint is used to retrieve file content:
<app web url>/_api//web/getfilebyserverrelativeurl('<file url>')/$value