Hello Everyone,
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");
-
-
- client.UploadValues("https://www.codeproject.com/script/Membership/LogOn.aspx?rp=%2f", values);
-
-
-
-
- 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");
-
- MessageBox.Show("ok");
- } catch (Exception e)
- {
- Console.WriteLine("{0}", e);
- MessageBox.Show("pas ok");
- }
- }
- }
- }
And when I run it, a "zip file" is downloaded but "corrupted". When I open it with the notepad, it looks like a html source code. So I added ".html" extension" and when I open it it shows the webpage which will start the downloading. If I wait a bit my browser try to download the file but it fails because it's from my ".html" file.
What am I doing wrong to download the html source code and not the file ?
Thanks in advance.