从URL下载图像无法打开

时间:2018-12-25 15:49:11

标签: image c#-4.0 microsoft-teams

图片URI https://statics.teams.microsoft.com/evergreen-assets/stickerassets/teamsquatch-250x250/Teamsquatch_EmailOverload.png 该图像在浏览器中打开,但是当我使用以下c#代码下载该图像时,下载的文件无法在图像查看器中打开。

我想念什么吗?

public  void DownloadFile(string requestUri, string downloadFilePath, TimeSpan requestTimeout, string token = null)
        {
            using (var webResponse = GetWebResponse(requestUri, requestTimeout, token))
            {
                using (var streamReader = webResponse.GetResponseStream())
                {
                    using (Stream file = File.OpenWrite(downloadFilePath))
                    {
                        streamReader.CopyTo(file);
                    }
                }
            }
        }

        private static WebResponse GetWebResponse(string requestUri, TimeSpan requestTimeout, string token = null)
        {
            var webReq = (HttpWebRequest)WebRequest.Create(requestUri);
            webReq.Method = "GET";
            webReq.Timeout = (int)requestTimeout.TotalMilliseconds;
            webReq.ReadWriteTimeout = (int)requestTimeout.TotalMilliseconds;
            webReq.KeepAlive = true;
            webReq.UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36";
           
            var httpResponse = (HttpWebResponse)webReq.GetResponse();
            return httpResponse;
        }

1 个答案:

答案 0 :(得分:0)

使用在线工具http://checkfiletype.com/检查了响应后,发现我们得到的内容是gzip,因此找到了解决方案。

我们可以应要求设置解压缩,然后设置以下内容,它将自动解压缩并将文件保存为png: webReq.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;