Download File From SharePoint 365

I was facing the same issue and tried the answer suggested by Vadim Gremyachev. However, it still kept giving 403 error. I added two extra headers to force form based authentication like below:

client.Headers.Add("X-FORMS_BASED_AUTH_ACCEPTED", "f");
client.Headers.Add("User-Agent: Other");

After this it started working. So the full code goes like below:

const string username = "[email protected]";
const string password = "password";
const string url = "https://tenant.sharepoint.com/";
var securedPassword = new SecureString();
foreach (var c in password.ToCharArray()) securedPassword.AppendChar(c);
var credentials = new SharePointOnlineCredentials(username, securedPassword);

DownloadFile(url,credentials,"/Shared Documents/Report.xslx");


private static void DownloadFile(string webUrl, ICredentials credentials, string fileRelativeUrl)
{
     using(var client = new WebClient())
     {
        client.Headers.Add("X-FORMS_BASED_AUTH_ACCEPTED", "f");
        client.Headers.Add("User-Agent: Other");
        client.Credentials = credentials;
        client.DownloadFile(webUrl, fileRelativeUrl);
     }  
}

Leave a Comment