C#网络编程之WebClient

1.什么是WebClient?

   源自MSDN:提供用于将数据发送到由 URI 标识的资源及从这样的资源接收数据的常用方法。

2.OpenRead()  为从具有String指定的URI的资源下载的数据打开一个可读的流。  

    需要先引用System.Net和System.IO. 

        public  static void GetPage(string uri)
        {
            WebClient wc = new WebClient();
            Stream stream = wc.OpenRead(uri);  //OpenRead的返回类型是Stream
            using (StreamReader sr = new StreamReader(stream))  
            {
                string line = "";
                while ((line=sr.ReadLine())!=null)
                {
                    Console.WriteLine(line);
                }
            }
        }

3.OpenWrite()  打开一个流以将数据写入指定的资源.

public void SendData(string uri, string content)
        {
           WebClient wc=new WebClient();
            Stream stream = wc.OpenWrite(uri);
            using (StreamWriter sw = new StreamWriter(stream))
            {
                sw.Write(content);
            }
        }


4.DownloadFile() 将具有指定 URI 的资源下载到本地文件。

 

WebClient wb = new WebClient();
wc.DownloadFile("http://www.xx.com", "xx.html");

 异步下载:

WebClient wc = new WebClient();
wc.DownloadProgressChanged += (sender, args) => Console.WriteLine(args.ProgressPercentage+ "% complete");
Task.Dealy(10000).ContinueWith(ant => wc.CancelAsync());  //如果超过限制时间,则取消下载
await wc.DownloadFileTaskAsync("http://www.xx.com", "xx.html"); // await 是C# 5.0中实现异步操作的关键字

 

  

 

posted @ 2015-06-18 11:34  豆腐爱鱼儿  阅读(1306)  评论(0编辑  收藏  举报