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中实现异步操作的关键字

 

  

 

转载于:https://www.cnblogs.com/wingswang/p/4584541.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值