Image URL has the contentType "text/html"

Posted by user1503025 on Stack Overflow See other posts from Stack Overflow or by user1503025
Published on 2012-09-29T03:21:08Z Indexed on 2012/09/29 3:37 UTC
Read the original article Hit count: 168

I want to implement a method to download Image from website to laptop.

public static void DownloadRemoteImageFile(string uri, string fileName)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
if ((response.StatusCode == HttpStatusCode.OK ||
            response.StatusCode == HttpStatusCode.Moved ||
            response.StatusCode == HttpStatusCode.Redirect) &&
            response.ContentType.StartsWith("image", StringComparison.OrdinalIgnoreCase))
        {
             //if the remote file was found, download it
            using (Stream inputStream = response.GetResponseStream())
            using (Stream outputStream = File.OpenWrite(fileName))
            {
                byte[] buffer = new byte[4096];
                int bytesRead;
                do
                {
                    bytesRead = inputStream.Read(buffer, 0, buffer.Length);
                    outputStream.Write(buffer, 0, bytesRead);
                } while (bytesRead != 0);
            }
        }
}

But the ContentType of request or response is not "image/jpg" or "image/png". They're always "text/html". I think that's why after I save them to local, they has incorrect content and I cannot view them.

Can anyone has a solution here? Thanks

© Stack Overflow or respective owner

Related posts about c#

Related posts about httpwebrequest