抛出异常的原因是http协议默认的并发访问量是2,但是当长时间访问网络不好,或者数据量较大的路径时候就会很快消耗完访问次数,所以解决办法如下(另外附上一个简单的下载方法,网上多的是):、
System.Net.ServicePointManager.DefaultConnectionLimit = 999;(999这个数字是随便写的,一般情况下512就够了,最大建议不要超过1024)
///
///下载方法
///serverPath为网络要下载的路径
public static void Download(string serverPath)
{
WebClient client = new WebClient();
HttpWebRequest myRequest = null;
string fileName = "概预算表.xls";//被下载的文件名
serverPath= "另存为路径" + fileName;//另存为地址
FileStream writeStream = new FileStream(path, FileMode.Append, FileAccess.Write, FileShare.ReadWrite);
try
{
myRequest = (HttpWebRequest)HttpWebRequest.Create(serverPath);//url地址 http://******
System.Net.ServicePointManager.DefaultConnectionLimit = 999;/*---------这里最重要--------*/
Stream readStream = myRequest.GetResponse().GetResponseStream();
byte[] btArray = new byte[512];
int contentSize = readStream.Read(btArray, 0, btArray.Length);
while (contentSize > 0)
{
writeStream.Write(btArray, 0, contentSize);
contentSize = readStream.Read(btArray, 0, btArray.Length);
}
//GC.Collect();
GC.WaitForPendingFinalizers();
//关闭流
writeStream.Close();
readStream.Close();
}
catch (Exception ex)
{
writeStream.Close();
System.Windows.Forms.MessageBox.Show(ex.Message, "提示");
}
}