WebClient.DownloadData hangs
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.
I think it maybe your own problem since my app does not hang. Here is my code sample. Could you post your code here?
System.Net.WebClient client = new System.Net.WebClient();
string url = @"http://www.daikodo.com/genki-back/back-img/10genki-2.jpg";
string savePath = @"C:\Temp\test.jpg";
Console.WriteLine("Downloading from: " + url);
byte[] result = client.DownloadData(url);
System.IO.File.WriteAllBytes(savePath, result);
Console.WriteLine("Download is done! It has been saved to: " + savePath);
Console.ReadKey();
I just had the same problem with long delays in my downloads, for me it was because i added a check to see if the uri was valid. if someone runs into the same problem check your other web requests like URI checking.
精彩评论