您的位置:首页 > 编程语言 > C#

C#访问网页、保存网页

2015-10-03 15:02 483 查看
很喜欢看经典书籍,所以就想把网络上的书籍下载下来,做成kindle的电子书籍,以便于阅读。查了一些网络资料,实现了自己的想法,下面这段代码,是从国学导航网站(http://www.guoxue123.com)把《北史》的全部内部保存到本地的“C:\temp\北史”文件夹里。《北史》共100卷,DownloadFile函数每次下载一卷,所以用一个循环执行100次把所有卷都存下来。

using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Net;

namespace history
{
class Program
{

//url 下载文件,filename,下载后的保存文件
public static void DownloadFile(string URL, string filename)
{
HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(URL);
HttpWebResponse rps = (HttpWebResponse)req.GetResponse();

Stream st = rps.GetResponseStream();
Stream so = new FileStream(filename, FileMode.Create);

byte[] by = new byte[rps.ContentLength];
int osize = st.Read(by, 0, (int)by.Length);
while (osize > 0)
{
so.Write(by, 0, osize);
osize = st.Read(by, 0, (int)by.Length);
}
so.Close();
st.Close();
}

static void Main(string[] args)
{
string root = "http://www.guoxue123.com/shibu/0101/00bs/";
string target = "C:\\temp\\北史\\";

//北史共一百卷,卷一网址:http://www.guoxue123.com/shibu/0101/00bs/000.htm
//卷一百网址:http://www.guoxue123.com/shibu/0101/00bs/099.htm
for (int i = 0; i <= 99; i++)
{
string filename = string.Format("{0:D3}.htm", i);
DownloadFile(root+filename, target + filename);
}
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: