I'm trying to write a C# program that can login and download a file from a website.
Here is my code:
- using System;
- using System.Collections.Specialized;
- using System.Net;
- using System.Windows.Forms;
- namespace CodeProjectDownload
- {
- public class CookiesAwareWebClient : WebClient
- {
- public CookieContainer CookieContainer;
- public CookieContainer MyProperty
- {
- get { return CookieContainer; }
- set { CookieContainer = value; }
- }
- public CookiesAwareWebClient()
- {
- CookieContainer = new CookieContainer();
- }
- protected override WebRequest GetWebRequest(Uri address)
- {
- WebRequest request = base.GetWebRequest(address);
- ((HttpWebRequest)request).CookieContainer = CookieContainer;
- return request;
- }
- }
- public class Program
- {
- private static void Download(string email, string password, string destination, string downloadUri)
- {
- using (CookiesAwareWebClient client = new CookiesAwareWebClient())
- {
- NameValueCollection values = new NameValueCollection();
- values.Add("Email",email );
- values.Add("Password", password);
- values.Add("x", "10");
- values.Add("y", "10");
- values.Add("login", "login");
- // We authenticate first
- client.UploadValues("https://www.codeproject.com/script/Membership/LogOn.aspx?rp=%2f", values);
- // Now we can download
- //string modifieduri = "http://www.codeproject.com/script/articles/download.aspx?file=" + downloadUri.Replace("http://www.codeproject.com","") + "&rp=";
- string modifieduri = "https://www.codeproject.com/KB/buttons/1087610/FontAwesomeImageSample.zip";
- Console.WriteLine("url " + modifieduri);
- string filename = System.IO.Path.GetFileName(downloadUri);
- string filepathname = System.IO.Path.Combine(destination, filename);
- client.DownloadFile(modifieduri, filepathname);
- }
- }
- static void Main(string[] args)
- {
- try
- {
- Download("[email protected]", "mfAwItJZ9+xZ", @"C:\Users\lswennen\Work Folders\WIP\Archiving\BIMCo connection", "/KB/buttons/1087610/FontAwesomeImageSample.zip");
- //Console.ReadLine();
- MessageBox.Show("ok");
- } catch (Exception e)
- {
- Console.WriteLine("{0}", e);
- MessageBox.Show("pas ok");
- }
- }
- }
- }
What am I doing wrong to download the html source code and not the file ?
Thanks in advance.
Amin MemarPosted Apr 16, 2020, 4:43 PM