I want to download an image from an URL.
My class:
public class MyWebClient : WebClient
{
public TimeSpan Timeout { get; set; }
protected override WebRequest GetWebRequest(Uri uri)
{
WebRequest request = base.GetWebRequest(uri);
request.Timeout = (int)Timeout.TotalMilliseconds;
((HttpWebRequest)request).ReadWriteTimeout = (int)Timeout.TotalMilliseconds;
return request;
}
}
And my method:
public void DownloadImage(string _url, string filename)
{
try
{
var timeout = TimeSpan.FromMinutes(5);
using (var webClient = new MyWebClient { Timeout = timeout })
{
byte[] imageData = webClient.DownloadData(_url);
File.WriteAllBytes(filename, imageData);
}
}
catch (Exception ex)
{
}
}
My test:
string url = "http://wallpaperswide.com/download/a_wooden_house_forest-wallpaper-1440x900.jpg";
DownloadImage(url, @"D:\test.jpg");
The size of the downloaded file is wrong and I cannot open the image file. I used a PictureBox
control to load the image from the URL, but it's not working either.
When I use a web browser control it works.
What is my problem?