Click here to Skip to main content
15,885,032 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:

http://doanhnhan.net/Resources/Data/News/huyenct/th%C3%A1ng%209/24/kinh%20t%E1%BA%BF/TMDT2.JPG

But it work with this url with www.
http://www.doanhnhan.net/Resources/Data/News/huyenct/th%C3%A1ng%209/24/kinh%20t%E1%BA%BF/TMDT2.JPG

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,
TuanNM
Posted
Updated 22-Mar-12 6:34am
v5
Comments
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?
TuanNM
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.:
http://doanhnhan.net/Resources/Data/News/huyenct/th%C3%A1ng%209/24/kinh%20t%E1%BA%BF/TMDT2.JPG
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.
C#
try
{
    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
 
Comments
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: omron-yte.vn/wp-content/uploads/HE-220.jpg is redirect to omron-yte.com.vn/wp-content/uploads/HE-220.jpg
And Firefox is still work :)
TuanNGUYEN 21-Mar-12 11:52am    
Just tested, the program can work with both: omron-yte.vn/wp-content/uploads/HE-220.jpg and omron-yte.com.vn/wp-content/uploads/HE-220.jpg

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