How can i download an excel file from sharepoint server? - c#

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?

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

Related

Download File From SharePoint 365

string remoteUri = "http://www.contoso.com/library/homepage/images/";
string fileName = "ms-banner.gif", myStringWebResource = null;
// Create a new WebClient instance.
WebClient myWebClient = new WebClient();
// Concatenate the domain with the Web resource filename.
myStringWebResource = remoteUri + fileName;
Console.WriteLine("Downloading File \"{0}\" from \"{1}\" .......\n\n", fileName, myStringWebResource);
// Download the Web resource and save it into the current filesystem folder.
myWebClient.DownloadFile(myStringWebResource,fileName);
Console.WriteLine("Successfully Downloaded File \"{0}\" from \"{1}\"", fileName, myStringWebResource);
Console.WriteLine("\nDownloaded file saved in the following file system folder:\n\t" + Application.StartupPath);
I'am Using this code from MSDN Web Site
But I have coming across the error: 403 forbidden
Can someone Help me Put this working ?
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 = "username#tenant.onmicrosoft.com";
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);
}
}
This error occurs since the request is not authenticated. In order to access resource in Office/SharePoint Online you could utilize SharePointOnlineCredentials class from SharePoint Server 2013 Client Components SDK (user credentials flow).
The following example demonstrates how to download a file from SPO:
const string username = "username#tenant.onmicrosoft.com";
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.Credentials = credentials;
client.Headers.Add("X-FORMS_BASED_AUTH_ACCEPTED", "f");
client.DownloadFile(webUrl, fileRelativeUrl);
}
}

View a PDF from SSRS / RDL

I want to access an RDL to obtain the report as PDF. I have
static void Main()
{
string pdfOutputFIleName = #"C:\Development\testoutputAsPdf.pdf";
var urlAsPdf = #"http://serverName/ReportServer/Reserved.ReportViewerWebControl.axd?ExecutionID=xxx&Culture=1033&CultureOverrides=False&UICulture=9&UICultureOverrides=False&ReportStack=1&ControlID=yyy&OpType=Export&FileName=Bug+Status&ContentDisposition=OnlyHtmlInline&Format=PDF";
var client = new WebClient();
client.UseDefaultCredentials = true;
//client.Headers.Add("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)");
client.Headers.Add("Content-Type", "application/pdf");
Process(client, urlAsPdf, pdfOutputFIleName);
Console.Read();
}
private static void Process(WebClient client, string url, string outputFileName)
{
Stream data = client.OpenRead(url);
using (var reader = new StreamReader(data))
{
string output = reader.ReadToEnd();
using (Stream s = File.Create(outputFileName))
{
var writer = new StreamWriter(s);
writer.Write(output);
Console.WriteLine(output);
}
}
}
The URL works fine in my browser. The program runs. When I to open the PDF I receive an error in Adobe:
There was an error opening this document. The file is damaged and
could not be repaired.
Since you already specify the output file name and the url to read from, perhaps you can use the WebClient.DownloadFile(string address, string filename) member.
private static void Process(WebClient client, string url, string outputFileName)
{
client.DownloadFile(url, outputFileName);
}

Sending SMS using clickatell in ASP.Net

I have tried this code from their site
using System.Net;
using System.IO;
WebClient client = new WebClient();
// Add a user agent header in case the requested URI contains a query.
client.Headers.Add("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)");
client.QueryString.Add("user", "xxxx");
client.QueryString.Add("password", "xxxx");
client.QueryString.Add("api_id", "xxxx");
client.QueryString.Add("to", "xxxx");
client.QueryString.Add("text", "This is an example message");
string baseurl = "http://api.clickatell.com/http/sendmsg";
Stream data = client.OpenRead(baseurl);
StreamReader reader = new StreamReader(data);
string s = reader.ReadToEnd();
data.Close();
reader.Close();
return s;
I am getting an Proxy authentication failure in
string baseurl ="http://api.clickatell.com/http/sendmsg";
Can anyone help me out??
I think you are behind a proxy and your web client needs to authenticate. Try the following code:
string userName = "<user name>";
string password = "<password>";
ICredentials creds = new NetworkCredential(userName, password);
client.Credentials = creds;

How to send HTTPS request from login box in C#

I am using c#, Microsoft AjaxToolKit.
I am using ajaxToolkit:ModalPopupExtender for the login page, now what I am trying that in my login page it should sent the HTTPS Request POST for the authentication of logging user. Below is the snapshot of my code on the click of login button.
protected void LoginBtn_Click(object sender, EventArgs e)
{
//Add your DB Authentication Module here....
//This is just for testing
if (loginId.Text.Equals("user") && pwd.Text.Equals("user"))
successLabel.Text = "Welcome User";
else
successLabel.Text = "Authentication Failed...Retry";
successLabel.Visible = true;
Loginlnk.Visible = false;
Signuplnk.Visible = true;
}
The above code is just for testing purpose, please suggest how can I proceed to have POST HTTPS WEB REQUEST to authenticate the valid user.
Thanks.
string username = "user";
string password = "pass";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://www.yoursite.com");
request.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; .NET CLR 1.0.3705)";
request.Method = "POST";
using (StreamWriter writer = new StreamWriter(request.GetRequestStream(), Encoding.ASCII))
{
writer.Write("nick=" + username + "&password=" + password);
}
Here is what works for me:
var request = WebRequest.Create(_url);
request.PreAuthenticate = true;
request.Credentials = new NetworkCredential(_userName, _password);

Automate downloads from password protected website [duplicate]

This question already has answers here:
Login to the page with HttpWebRequest
(2 answers)
Closed 6 years ago.
I need some help with a work project I have been assigned. At the moment we manually go to the site, logon and then download 2 excel files from a supplier's website every month. The files are then loaded into SQL.
We want to automate this process. Now the loading of the files into SQL I can do, but I am not sure how I can automate logging onto the website entering my user details and collecting the files. I mostly deal with SQL and have very little .NET experience, so any code samples would be most appreciated.
Just to confirm. The logon form is on a aspx page. just a basic form with a table containing the username & password fields, the forgotten password link and the logon button
You can either use webclient or httpwebrequest.
Login to the page with HttpWebRequest
How do you login to a webpage and retrieve its content in C#?
Httpwebrequest example:
HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create("http://sso.bhmobile.ba/sso/login");
req.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; .NET CLR 1.0.3705;)";
req.Method = "POST";
req.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
req.Headers.Add("Accept-Language: en-us,en;q=0.5");
req.Headers.Add("Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7");
req.KeepAlive = true;
req.Headers.Add("Keep-Alive: 300");
req.Referer ="http://sso.bhmobile.ba/sso/login";
req.ContentType = "application/x-www-form-urlencoded";
String Username = "username";
String PassWord = "Password";
StreamWriter sw = new StreamWriter(req.GetRequestStream());
sw.Write("application=portal&url=http%3A%2F%2Fwww.bhmobile.ba%2Fportal%2Fredirect%3Bjsessionid%3D1C568AAA1FB8B5C757CF5F68BE6ECE65%3Ftype%3Dssologin%26url%3D%2Fportal%2Fshow%3Bjsessionid%3D1C568AAA1FB8B5C757CF5F68BE6ECE65%3Fidc%3D1023278&realm=sso&userid=" + Username + "&password=" + password + "&x=16&y=11");
sw.Close();
HttpWebResponse response = (HttpWebResponse)req.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream());
string tmp = reader.ReadToEnd();
foreach (Cookie cook in response.Cookies)
{
tmp += "\n" + cook.Name + ": " + cook.Value;
}
Response.Write(tmp);
Response.End();
Webclient example:
WebClient wc = new WebClient();
wc.Credentials = new NetworkCredential("username", "password");
string url = "http://foo.com";
try
{
using (Stream stream = wc.OpenRead(new Uri(url)))
{
using (StreamReader reader = new StreamReader(stream))
{
return reader.ReadToEnd();
}
}
}
catch (WebException e)
{
//Error handeling
}

Categories