您的位置:首页 > 理论基础 > 计算机网络

C#网络编程之WebClient

2015-06-18 11:34 531 查看
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中实现异步操作的关键字
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: