下面是我用来从多个服务器下载文件的方法。请注意,我已经设置了从响应流中读取多少的限制,因为如果我得到的文件超过了指定的大小,我不想全部读取它。在我的应用程序中,没有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();
}
}
我不知道这是否会解决您遇到的悬挂问题,但它适用于我的应用程序。
当您设置超时时间超时? – 2010-03-14 09:32:45
不,那是我的问题。我的过程只是挂起,直到我杀死它。 – sagie 2010-03-14 09:42:35
你可以发布你的下载代码吗?从目前的回应看,问题似乎更可能是您的连接而不是您的代码,但如果我们可以看到您的代码,它将有助于确认这一点。 – 2010-03-23 10:37:31