Reputation: 183
I have a project (c# console application), in which I want to automatically download an excel file, via URL, with login credentials.
I have been using a webclient to download the file automatically, and all I receive is an html page as response, informing me to login into the site (I have run it in Chrome.)
private static string url = "[the whole url link to the file, deleted for privacy]";
public void test()
{
const string username = "[mail]";
const string password = "[password]";
var securedPassword = new SecureString();
foreach (var c in password.ToCharArray())
{
securedPassword.AppendChar(c);
}
var credentials = new SharePointOnlineCredentials(username, securedPassword);
DownloadFile(url, credentials, @"C:\Documents\ExcelFilesSinc\test.xlsx");
}
private static void DownloadFile(string webUrl, ICredentials credentials, string fileRelativeUrl)
{
using (var client = new WebClient())
{
client.Credentials = credentials;
string _UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)";
client.Headers.Add(HttpRequestHeader.UserAgent, _UserAgent);
client.DownloadFile(webUrl, fileRelativeUrl);
}
}
In this way, the file is generated, but the whole content saved in it is an HTML page that requires me to login to Microsoft. Any suggestions?
Upvotes: 1
Views: 1235
Reputation: 924
You can try to add headers for base auth like
client.Headers.Add("X-FORMS_BASED_AUTH_ACCEPTED", "f");
client.Headers.Add("User-Agent: Other");
client.Credentials = credentials;
see also here: Download File From SharePoint 365
Upvotes: 1