Click here to Skip to main content
15,920,383 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi all,
I am programming an module downloading image, the code as below:

WebRequest wr = WebRequest.Create(url);
WebResponse ws = wr.GetResponse(); // => throw exception 404 with the below url
Stream dataStream = ws.GetResponseStream();

It throw an exception with url like:

But it work with this url with www.

In fact, Firefox/Chrome/IE work on both urls, with and without www.

How can I download the image like Firefox do?
Thank in advance,
Updated 22-Mar-12 6:34am
Wayne Gaylard 21-Mar-12 5:04am    
I have just tried it and it works for me. Must be something going wrong before this code I think.
TuanNGUYEN 21-Mar-12 5:48am    
Thank for answer,
I've tried unit test its, just 5 lines of code, it doesn't work with the url (and work with other non-unicode url).
Did you try the url that I give?
Bernhard Hiller 21-Mar-12 6:03am    
The URL above is ok. I guess you tried with the URL containing Vietnamese characters instead of those ""%C3%A0...".
TuanNGUYEN 21-Mar-12 7:14am    
Oh, i work with the url with www.
Anh wrong the the url without www.:
How can I adjust the url without www., because Firefox can display the url without www.

1 solution

Do a try...catch arong the wr.GetResponse. If you catch an exception, find out if it is a "404 not found". In that case, add a "www." and try again, e.g.
    System.Net.WebResponse ws = wr.GetResponse();
catch (System.Net.WebException wex)
    System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex("\b404\b");
    System.Text.RegularExpressions.Match match = regex.Match(wex.Message);
    if (match.Success)
        //change URL
Share this answer
TuanNGUYEN 21-Mar-12 11:42am    
Thank for your answer,
But I think it is not the way that browsers do.
Because sometime, the url can be redirected to a very different url, but firefox/chrome still work okie.
Ex: is redirect to
And Firefox is still work :)
TuanNGUYEN 21-Mar-12 11:52am    
Just tested, the program can work with both: and

Now, i dont know why it doesn't work with the url without www but Firefox work :(

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900