Mr Alemi
Mr Alemi

Reputation: 850

Download Image From Url not Working Well C#

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?

Upvotes: 1

Views: 1174

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038800

It looks like this particular website from which you are trying to download expects a User-Agent header to be specified, otherwise it just returns some html instead of the image. So you could trick it into thinking that it is a browser making the request and you will get the expected image back:

webClient.Headers["User-Agent"] = "User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36";
var imageData = webClient.DownloadData(_url);

Upvotes: 1

Related Questions