gpt4 book ai didi

c# - WebClient.DownloadData 挂起

转载 作者:行者123 更新时间:2023-11-30 18:09:30 24 4
gpt4 key购买 nike

我正在尝试使用 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com