1
Reply

Check if URL exists, and then download file...

Carlos

Carlos

Feb 13 2009 9:39 AM
16.3k
Hi there,

So...what I want to do, is to check if a certain URL is valid/exists, so I can download the file from that same URL.
If the URL has a custom 404 page there's really no problem because if this is the case, I'm able to download the file and then I can check if it's the one I want. If the URL has not a custom page, however, then I'm using WebRequest/WebResponse.
This is my code:

//-> Check if url is valid 
WebRequest serverRequest = WebRequest.Create(_url); 
WebResponse serverResponse; 
try //Try to get response from server 
    serverResponse = serverRequest.GetResponse(); 
catch //If could not obtain any response 
    return 0; 
 
WebClient _client = new WebClient(); 
_client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(_client_DownloadProgressChanged);
 
_client.DownloadFileAsync(new Uri(_url), _destinationPath); //Download the file. 


So, if the URL gets a valid response from 'serverResponse' then it downloads the file, and I can later check if it's the one I want.
This all seems OK (I guess), and it works just fine......IF you only run this code once!

Let's suppose the URL is valid. If I put the code above in a button click event, for example, when I click the button the first time, it downloads the file and everything is OK. However, if I click the button a second time (after the first file has been successfully downloaded), it just creates a file with 0 kb, overwriting the previous one, and doesn't even go for the download.

I have no idea why this is happening...the only thing I know, is that it is due to the WebRequest/WebResponse part, because if I remove it, it goes just fine...but then I can't check for a valid URL.

Is there any other way to check if the URL is valid? Or does anyone knows what's really happening?


I really appreciate any help here.
Carlos

p.s. sorry if this is not the right section...

Answers (1)