My program uses WebRequest
and WebResponse
in order to download a HTML file from a given URL in an iteration. For example, the URL string will look something like
http://www.aaaa.com/cccc=
varB
where varB
is a different string for each iteration through the loop.
After it downloads the file into a stream, it would search the stream for specific strings of text and store them into a separate text file. However, I found that on some iterations it doesn't seem to be reading anything (the URL string for it is valid when I type it into the address bar, so it's not an invalid URL).
I put the streams and WebResponse
objects in using
blocks, and I also have a try…catch
block, but no exception occurs. Is using WebRequest
and WebResponse
problematic within loops?
try
{
foreach (string name in names)
{
string urlstr = "…"; // URL format like I mentioned earlier
HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(urlstr);
myRequest.Timeout = 30000;
//store the response in myResponse
using (HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse())
{
//register I/O stream associated with myResponse
using (Stream myStream = myResponse.GetResponseStream())
{
//create StreamReader that reads characters one at a time
using (StreamReader myReader = new StreamReader(myStream))
{
myReader.ReadLine();
sw.WriteLine(name + " " + myReader.ReadLine());
}
}
}
}
sw.Close();
}
The result will look similar to this:
name1 stuffReadfromfile
name2 stuffReadfromfile
name3 stuffReadfromfile
name4
name5 stuffReadfromfile
name6
name7 stuffReadfromfile
name8 stuffReadfromfile
name9
name10 stuffReadfromfile
even though there should be stuffReadfromfile
after each name.