C#网络编程

文件下载

首先保存文件的后缀名,一定要和原文件相同。

下载文件有很多方式:

方式1——通过文件流下载:

获得下载文件的数据流:

HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
//GetResponse方法,向url发送请求并获取相应回应数据
HttpWebResponse response = request.GetResponse() as HttpWebResponse;  //最后,最好还是将response关闭
Stream responseStream = response.GetResponseStream();  //必须写成Stream对象,因为GetResponseStream方法返回的Stream对象无法装换成其他对象

将这些数据流保存在本地(完成之后,就可以得到想要的文件,这就是所谓的下载):

FileStream stream = new FileStream("F:/shutao.exe", FileMode.Create);
byte[] arr = new byte[102400];
int size = responseStream.Read(arr, 0, arr.Length);
while (size > 0)
{
    stream.Write(arr, 0, size); //读多少,写多少
    size = responseStream.Read(arr, 0, arr.Length);
}
stream.Close();
response.Close();

最后记得将网络数据流Close掉,就像本地文件流一样。

上面是文件的获取,举一反三的可以获得网页的源代码或者其他文本的内容:

private void button1_Click(object sender, EventArgs e)
{
    Uri uri = new Uri("http://www.cnblogs.com/quanxi/p/6227517.html");
    HttpWebRequest request = WebRequest.Create(uri) as HttpWebRequest;
    HttpWebResponse response = request.GetResponse() as HttpWebResponse;
    Stream httpStream = response.GetResponseStream();
    StreamReader reader = new StreamReader(httpStream);
    
    StreamWriter writer = new StreamWriter("F:/liuyiwei.html");
    writer.Write(reader.ReadToEnd());
    writer.Close();
    reader.Close();
    httpStream.Close();
    response.Close();
}

读取XML:

LINQ to XML

posted @ 2017-01-15 22:04  不抛弃,不放弃  阅读(478)  评论(0编辑  收藏  举报