using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
namespace SH600004Quickly
{
class Program
{
static void Main(string[] args)
{
WebClient webClient = new WebClient();
ServicePointManager.DefaultConnectionLimit = 100;
string Start = "2010年04月13日";
string End = "2013年12月31日";
DateTime dtStart = DateTime.Parse(Start);
DateTime dtEnd = DateTime.Parse(End);
int Days = (dtEnd - dtStart).Days + 1;//相隔天数
string strPath = "F:\\gupiao111111\\";
string Stockid = "600000";
//string aFirstName = args[0].Substring(args[0].LastIndexOf("\\") + 1, (args[0].LastIndexOf(".") - args[0].LastIndexOf("\\") - 1));
for (int i = 0; i < Days; i++)
{
string url = null;
string sDay = dtStart.AddDays(i).ToString("yyyy-MM-dd"); //每一天
url = "http://market.finance.sina.com.cn/downxls.php?date=" + sDay + "&symbol=sh" + Stockid;
Console.WriteLine(url);
DirectoryInfo stockDir = Directory.CreateDirectory(strPath + sDay);
string dataDir = stockDir.FullName + "\\data.txt";
webClient.DownloadFile(url, dataDir);
//webClient.Dispose();
//WriteStr2FileEnd("C:\\Users\\T.Yang\\Desktop\\errorLog.txt", sDay + " " + aFirstName);
//strPath = "F:\\gupiao111111\\";
}
//将每个文件夹里的文件用bat处理
}
public static void WriteStr2FileEnd(String filename, String content)//自动换行写入
{
FileStream fsLineNo = new FileStream(@filename, System.IO.FileMode.OpenOrCreate, FileAccess.Write);
fsLineNo.Seek(fsLineNo.Length, SeekOrigin.Begin);
StreamWriter swLineNo = new StreamWriter(fsLineNo);
swLineNo.WriteLine(content);
swLineNo.Close();
fsLineNo.Close();
}
}
}
每次下载几个文件后,就卡在那不动了,怎么办?
WebClient webClient = new WebClient(); 把这个放FOR循环里面试试?
可能原因:
由于默认连接是2个,超过将阻塞。加上即使对象过了作用区,垃圾并没有即使释放,连接一直保持,所以一直苦恼这个原因。
一般出现在循环请求响应或循环下载中。程序将一直等待(默认100秒),由于连接一直没释放(垃圾回收没来得及回收)就一直阻塞。
解决办法(绝大多数能解决):
1、设置最大连接数50甚至更大。
System.Net.ServicePointManager.DefaultConnectionLimit = 100;
2、把KeepAlive设置为false,不让它一直保持连接。
webclient对象.keepalive=false
3、请求完毕后,立即释放(对象或流必须关闭或释放)
webclient对象.close(或者dispose,或者abort)
4、使用请求或下载前,强行用垃圾进行回收。
GC.collect
5、使用请求或下载前,请等待几秒(不用sleep)
用do...loop...来确定等待几秒。
6、确信下载或请求的源一定存在时,用try捕捉失败时再试一次下载。