I am creating a program in c# using webbrowser control to view moodle of my university. I am downloading files using public class CookieAwareWebClient.class (found this code in internet to download authorized files) but i cant get correct file name or some links example - http://somewebsite.com/mod/resource/view.php?id=80824 . When i click this in my regular chrome browser pdf file "http://somewebsite.com/pluginfile.php/186873/mod_resource/content/1/somefile.pdf" opens. but i cant het the name "somefile.pdf" .How i can get the original file name "somefile.pdf".
my function to download files
public void saveFile(String url)
{
Uri Url = new Uri(@url);
String filePath = "c:\\";
fileName = url.Substring(url.LastIndexOf("/") + 1).Replace("%20", " ").Replace("%28", " ").Replace("%29", " ");
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.FileName = fileName;
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
filePath = saveFileDialog1.FileName;
CookieAwareWebClient http = new CookieAwareWebClient(new CookieContainer());
http.DownloadProgressChanged += new DownloadProgressChangedEventHandler(client_DownloadProgressChanged);
http.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
string response = http.UploadString("http://courseweb.sliit.lk/login/index.php", "username=" + Form1.USERNAME + "&password=" + Form1.PASSWORD + "&submit=submit");
//http.DownloadFile(Url, filePath);
http.DownloadFileAsync(Url, filePath);
this.Text = "Downloading File - " + fileName;
}
}
my CookieAwareWebClient.class below
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
namespace Course_Web
{
public class CookieAwareWebClient : WebClient
{
Uri target = new Uri("http://unversitywebsite.com");
public CookieContainer CookieContainer { get; set; }
public Uri Uri { get; set; }
public CookieAwareWebClient()
: this(new CookieContainer())
{
}
public CookieAwareWebClient(CookieContainer cookies)
{
this.CookieContainer = cookies;
}
protected override WebRequest GetWebRequest(Uri address)
{
WebRequest request = base.GetWebRequest(address);
if (request is HttpWebRequest)
{
(request as HttpWebRequest).CookieContainer = this.CookieContainer;
}
HttpWebRequest httpRequest = (HttpWebRequest)request;
httpRequest.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
return httpRequest;
}
protected override WebResponse GetWebResponse(WebRequest request)
{
WebResponse response = base.GetWebResponse(request);
String setCookieHeader = response.Headers[HttpResponseHeader.SetCookie];
if (setCookieHeader != null)
{
//do something if needed to parse out the cookie.
if (setCookieHeader != null)
{
Cookie cookie = new Cookie("CookieName", "CookieValue") { Domain = target.Host }; //create cookie
this.CookieContainer.Add(cookie);
}
}
return response;
}
}
}