WebClient.DownloadData freezes

I am trying to upload a file using WebClient.DownloadData. Normally, the download will work fine, but for some URLs the download will simply freeze.

I tried to override WebClient and set a timeout for WebRequest, and that didn't help.

I also tried to create a WebRequest (with a timeout), then get a WebResponse, and then get a stream. When I read the stream, it freezes again.

This is an example of a URL that hangs: http://www.daikodo.com/genki-back/back-img/10genki-2.jpg .

Any idea?

+3
source share
3 answers

. , , , , , , . URL- ; .

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();
    }
}

, , .

+1

, , . . ?

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();
0

, , , , . - , -, URI.

0
source

Source: https://habr.com/ru/post/1736867/


All Articles