using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using System.Diagnostics;
namespace ParallelPerday
{
class Program
{
static void Main(string[] args)
{
string Start = "2010年1月1日";
string End = "2013年12月31日";
DateTime dtStart = DateTime.Parse(Start);
DateTime dtEnd = DateTime.Parse(End);
int Days = (dtEnd - dtStart).Days + 1;//相隔天數
string aFirstName = args[0].Substring(args[0].LastIndexOf("\") + 1, (args[0].LastIndexOf(".") - args[0].LastIndexOf("\") - 1));//取文件名為以6000,30,或00開頭的文件名,不包括後綴,例如600004.txt,只要600004
Stopwatch watch = new Stopwatch();
watch.Start();
Parallel.For(0, Days, i =>
{
WebClient webClient = new WebClient();
webClient.Proxy = null;
string strPath = "F:\\Stock Data(2303)\\";//下載到本地的路徑
string url = null;
string sDay = dtStart.AddDays(i).ToString("yyyy-MM-dd"); //獲得以2010年1月1日以後的每一天,如2010-1-31
if (aFirstName.Substring(0, 3).Equals("600") || aFirstName.Substring(0, 3).Equals("601"))
{
url = "http://market.finance.sina.com.cn/downxls.php?date=" + sDay + "&symbol=sh" + aFirstName;//下載的網址鏈接(拼接而成)
strPath = strPath + "sh" + aFirstName + "\\";
}
if (aFirstName.Substring(0, 3).Equals("300") || aFirstName.Substring(0, 2).Equals("00"))
{
url = "http://market.finance.sina.com.cn/downxls.php?date=" + sDay + "&symbol=sz" + aFirstName;//下載的網址鏈接
strPath = strPath + "sz" + aFirstName + "\\";//下載到本地的路徑
}
try
{
DirectoryInfo stockDir = Directory.CreateDirectory(strPath + sDay);//創建文件夾
string dataDir = stockDir.FullName + "\\data.txt";//下載到本地的路徑
webClient.DownloadFile(url, dataDir);
}
catch (Exception)
{
Console.WriteLine(aFirstName + " " + sDay);
}
finally
{
webClient.Dispose();
}
});
watch.Stop();
Console.WriteLine(string.Format("Normal For Cost Time:{0}", watch.ElapsedMilliseconds));
}
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();
}
}
}
如果一開始可以下載,估計和你的網絡有關系,試試這個斷點續傳的代碼
http://biancheng.dnbcw.info/c/43086.html