Ustawia limit czasu dla webClient.Pobierz plik()

Używam webClient.DownloadFile() do pobrania pliku Czy Mogę ustawić limit czasu na to, aby nie trwało to długo, jeśli nie może uzyskać dostępu do pliku?

Author: abatishchev, 2009-03-02

3 answers

Spróbuj WebClient.DownloadFileAsync(). Możesz wywołać CancelAsync() przez timer z własnym timeoutem.

 40
Author: abatishchev,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2009-03-02 10:39:22

Moja odpowiedź pochodzi z TUTAJ

Możesz utworzyć klasę pochodną, która ustawi właściwość timeout podstawowej klasy WebRequest:

using System;
using System.Net;

public class WebDownload : WebClient
{
    /// <summary>
    /// Time in milliseconds
    /// </summary>
    public int Timeout { get; set; }

    public WebDownload() : this(60000) { }

    public WebDownload(int timeout)
    {
        this.Timeout = timeout;
    }

    protected override WebRequest GetWebRequest(Uri address)
    {
        var request = base.GetWebRequest(address);
        if (request != null)
        {
            request.Timeout = this.Timeout;
        }
        return request;
    }
}

I możesz go używać tak jak podstawowej klasy WebClient.

 248
Author: Beniamin,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-08-14 17:23:26

Zakładając, że chcesz to zrobić synchronicznie, używając WebClient.OpenRead(...) metoda i ustawienie timeoutu na strumieniu, który zwraca, da pożądany wynik:

using (var webClient = new WebClient())
using (var stream = webClient.OpenRead(streamingUri))
{
     if (stream != null)
     {
          stream.ReadTimeout = Timeout.Infinite;
          using (var reader = new StreamReader(stream, Encoding.UTF8, false))
          {
               string line;
               while ((line = reader.ReadLine()) != null)
               {
                    if (line != String.Empty)
                    {
                        Console.WriteLine("Count {0}", count++);
                    }
                    Console.WriteLine(line);
               }
          }
     }
}

Wyprowadzenie z WebClient i nadpisanie GetWebRequest(...) aby ustawić timeout @ Beniamin zasugerował ,nie zadziałało dla mnie jak, ale to tak.

 3
Author: jeffrymorris,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-01-25 18:37:20