I am trying to download file using WebClient.DownloadData. Usually the download is Ok, but for some Urls the download just hangs.
I've tried to override the WebClient, and set a timeout to the WebRequest, and it didn't help.
I've also tried to create WebRequest (with time out), then get the WebResponse, and then get the stream. When I've read the stream, It hangs again.
This is an example for a url that hangs: http://www.daikodo.com/genki-back/back-img/10genki-2.jpg.
Any Idea?
Here's what I use to download files from multiple servers. Note that I have set a limit to how much I want to read from the response stream because in the event I get a file exceeding the specified size, I don't want to read all of it. In my application, no URL's should result in a file exceeding the size; you may omit this limitation or increase this amount as needed.
int MaxBytes = 8912; // set as needed for the max size file you expect to download
string uri = "http://your.url.here/";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
request.Timeout = 5000; // milliseconds, adjust as needed
request.ReadWriteTimeout = 10000; // milliseconds, adjust as needed
using (var response = request.GetResponse())
{
using (var responseStream = response.GetResponseStream())
{
// Process the stream
byte[] buf = new byte[1024];
string tempString = null;
StringBuilder sb = new StringBuilder();
int count = 0;
do
{
count = responseStream.Read(buf, 0, buf.Length);
if (count != 0)
{
tempString = Encoding.ASCII.GetString(buf, 0, count);
sb.Append(tempString);
}
}
while (count > 0 && sb.Length < MaxBytes);
responseStream.Close();
response.Close();
return sb.ToString();
}
}
I don't know if this will solve the hanging problem you are having, but it works well for my app.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With