繁体   English   中英

WebClient.DownloadData挂起

[英]WebClient.DownloadData hangs

我正在尝试使用WebClient.DownloadData下载文件。 通常下载是好的,但对于一些Urls,下载只是挂起。

我试图覆盖WebClient,并为WebRequest设置超时,但它没有帮助。

我还尝试创建WebRequest(超时),然后获取WebResponse,然后获取流。 当我阅读流时,它再次挂起。

这是一个挂起的网址示例: http//www.daikodo.com/genki-back/back-img/10genki-2.jpg

任何想法?

这是我用来从多个服务器下载文件的内容。 请注意,我已经设置了一个限制,我想从响应流中读取多少,因为如果我得到一个超过指定大小的文件,我不想读取所有文件。 在我的应用程序中,没有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();
    }
}

我不知道这是否能解决您遇到的悬挂问题,但它适用于我的应用程序。

我认为这可能是你自己的问题,因为我的应用程序没有挂起。 这是我的代码示例。 你能在这里发布你的代码吗?

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

在我的下载中,我遇到了同样的长时间延迟问题,对我来说,这是因为我添加了一个检查,看看uri是否有效。 如果有人遇到同样的问题,请检查您的其他Web请求,如URI检查。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM