Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/313.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
从Url下载图像不正常C#_C#_Image_Url_Download_Webclient - Fatal编程技术网

从Url下载图像不正常C#

从Url下载图像不正常C#,c#,image,url,download,webclient,C#,Image,Url,Download,Webclient,我想从URL下载图像 我的班级: public class MyWebClient : WebClient { public TimeSpan Timeout { get; set; } protected override WebRequest GetWebRequest(Uri uri) { WebRequest request = base.GetWebRequest(uri); request.Timeout = (int)Tim

我想从URL下载图像

我的班级:

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;
    }
}
我的方法是:

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)
    {
    }
}
我的测试:

string url = "http://wallpaperswide.com/download/a_wooden_house_forest-wallpaper-1440x900.jpg";

DownloadImage(url, @"D:\test.jpg");
下载的文件大小错误,我无法打开图像文件。我使用了
PictureBox
控件从URL加载图像,但它也不起作用

当我使用web浏览器控件时,它会工作


我的问题是什么?

看起来您试图从中下载的这个特定网站需要指定一个
用户代理
标题,否则它只返回一些html而不是图像。因此,您可以欺骗它,使其认为是浏览器发出请求,您将获得预期的图像:

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);