简体   繁体   中英

Retrieve image from an aspx URL

I am trying to get my Visual C# program to download an image from a URL that ends in .aspx. This image is actually a captcha code, and it changes with time.

What I have tried to do thus far is create a PictureBox, and I have set the ImageLocation to the ASPX url that returns an image.

However, this gives me nothing but a red boxed X where the captcha image should have appeared.

Is there some code I should type? Sorry for my lack of understanding, I'm a newbie at this C# business!

Thanks for all your help!

You can try downloading the image manually to see if you get a valid image

using (WebClient webclient = new WebClient())
{
    using (var imageStream = webclient.OpenRead("http://example.com/image.png"))
    {
        Image img = Image.FromStream(imageStream);                   
    }
}

If you don't get a valid image, you can then try var str = webclient.DownloadString("http://example.com/image.png"); and inspect the str variable to see if you get some error text data from the webserver instead of an image.

Thanks to everybody who has helped out in answering this question!

I was dealing with a rather picky server which would only allow clients with a valid user-agent to access the site it was hosting. Adding:

webclient.Headers["User-Agent"] = "Mozilla/5.0 (compatible; MSIE 8.0; Windows NT 6.0; SV1; .NET CLR 3.0.4506.2152; .NET CLR 3.0.30618)2011-09-18 00:09:44";

solved the problem.

Thanks!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM