我的项目赢了';t从网站上加载图像(C#)

我的项目赢了';t从网站上加载图像(C#),c#,timeout,httpwebrequest,C#,Timeout,Httpwebrequest,今天,在使用我几年前编写的一个程序时,我遇到了这样一种情况:加载网站的缩略图最终超时,而不是加载。我的网络浏览器能够很好地打开文件,经过几个小时的故障排除,我已经没有主意了 public static Image GetThumbNail(OnlineImageInfo info) { //Check if thumbnail has been cached to disk FileInfo file = new FileInfo(string.Forma

今天,在使用我几年前编写的一个程序时,我遇到了这样一种情况:加载网站的缩略图最终超时,而不是加载。我的网络浏览器能够很好地打开文件,经过几个小时的故障排除,我已经没有主意了

public static Image GetThumbNail(OnlineImageInfo info)
    {
        //Check if thumbnail has been cached to disk
        FileInfo file = new FileInfo(string.Format("{0}{1}", Config.ActiveConfig.ThumbnailCachePath.FullName,
            info.PreveiwFileName));
        if (!file.Exists)
        {
            //Generate a web request
            HttpWebRequest request = (HttpWebRequest) HttpWebRequest.Create(info.PreveiwURL);
            request.Method = "GET";

            request.UserAgent = ".NET Framework Test Client";
            request.Timeout = 10000; //I added the timeout to stop the program from hanging while trying to load this thumbnail
            WebResponse response = null;
            try
            {
                response = request.GetResponse();
                //cache the image to disk
                using (var fs = file.Create())
                {
                    using (var strm = response.GetResponseStream())
                    {
                        strm.CopyTo(fs);
                        fs.Flush();
                        fs.Close();
                    }
                }
            }
            catch (WebException e)
            {
                //timed out
                Console.WriteLine(e);
                throw;
            }
            finally
            {
                if (response != null)
                    response.Dispose();
            }


        }
        //Load image from disk to RAM
        Image result = null;
        MemoryStream mem = new MemoryStream();
        using (var fs = TryGetFileStream(file))
        {
            fs.CopyTo(mem);
            result = Image.FromStream(mem);
        }


        return result;
    }
奇怪的是,我从这个网站上下载了数千个缩略图,我以前从未遇到过这种情况。谁能想到为什么这个文件会在我的程序而不是浏览器上超时,或者我如何进一步排除故障

编辑: 在尝试了下面评论中的建议后,没有任何效果,我尝试将请求强制为Http而不是Https,结果发现它突然起作用了。我想弄清楚为什么我会有这种行为,但至少它现在起作用了

HttpWebRequest request = (HttpWebRequest) HttpWebRequest.Create(info.PreveiwURL.Replace("https:","http:"));
            request.Method = "GET";
            request.Referer = info.SourceWebsite;
            request.UserAgent = "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:60.0) Gecko/20100101 Firefox/60.0";
            request.Timeout = 5000;
            WebResponse response = null;

我会打开web浏览器网络监视器并检查重定向,这些重定向可能会改变所观察到的行为或指定一个真正的浏览器用户代理(可能是IE)。如果代码看起来很好,并且您没有提供一些基本调试,则您可能无法获得帮助。打开pgoram,在方法的开始处设置一个断点,然后一步一步地检查它。如果(!file.Exists),我怀疑它会进入
上的第一个块,因为如果它以前工作过,并且程序中没有任何更改,那么只会留下网站和目标数据…@bradbury9我尝试过使用IE和Fire Fox用户代理,但它仍然不工作。我在网络监视器上也看不到任何重定向。有时有些网站带有防止网络抓取的控件,以确保内容是面向实际用户的服务器,而不是程序/机器人。通常的方法是检查推荐信是否匹配其网站