I am trying to download 10 photos from an external link e.g http://images.net/images/20159178574IMG_0843.jpg
I am reading a text file on my drive and putting it on a list here is the code
List < string > lines = new List < string > ();
using(StreamReader r = new StreamReader(fileName))
{
string line;
while ((line = r.ReadLine()) != null)
{
lines.Add(line);
}
}
foreach(string s in lines)
{
getthefile(s, System.DateTime.Now.Hour + System.DateTime.Now.Minute + System.DateTime.Now.Second + ".jpg");
}
private void getthefile(string filename, string filenamesave)
{
if (checkurl(filename))
{
string filepath = @
"D:\files" + "\\Photos\\" + filenamesave;
WebClient webClient = new WebClient();
webClient.DownloadFile(filename, filepath);
}
}
private bool checkurl(string url)
{
var request = (HttpWebRequest) WebRequest.Create(url);
request.Method = "HEAD";
var response = (HttpWebResponse) request.GetResponse();
switch ((int) response.StatusCode)
{
case 200:
return true;
default:
return false;
}
}
Now the first photo on the list gets downloaded but when the loop moves to the next photo it gets stuck for about 2 minutes and throws a timeout exception I tried making a new list to see if it the error occurs again but sadly it throws the same error.
is there something wrong with my code or the server hosting the IIS?
thank you
It looks like your problem is in the checkurl
method, which doesn't dispose of the WebResponse
that it gets - that means the connection pool associated with that host has effectively "lost" that connection until the WebResponse
gets finalized. Basically, always use a using
statement with WebResponse
objects.
Aside from that, it's not clear why you want to make two requests for each URL anyway - nor whether your checkurl
is actually going to return false
when you encounter an error, rather than throwing an exception. I'd just skip the checkurl
test, try to download the file, and handle any exceptions thrown by WebClient
instead.
See more on this question at Stackoverflow