c# - WebClient.DownloadData 挂起

标签 c# download webclient

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

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

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

这是一个挂起的 url 的示例: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();
    }
}

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

关于c# - WebClient.DownloadData 挂起,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2441674/

相关文章:

c# - 使用进度从 FTP 下载文件 - TotalBytesToReceive 始终为 -1?

.net - 将整个文件夹上传到FTP的PowerShell脚本

c# - 为什么从我的代码中删除 TextBox.AppendText() 会更改此处的套接字通信?

c# - 对象收集位置的 Linq 结果

c# - 匹配 M/YYYY、MM/YYYY、M/YY 或 MM/YY 格式的正则表达式

asp.net-mvc - Mvc - 返回文件和刷新页面

android - 如何从单独的线程正确调用 AsyncTask?

c# - 绑定(bind)到内部属性?

curl - 如何将 --range 与 --continue 与 cURL 一起使用?

java - 如何使用httpunit获取json页面