WebClient的使用示例

1.OpenRead()

    从Web站点检索数据,使用OpenRead()方法返回一个Stream引用。ReadLine()方法从数据流中以文本的形式获取数据。

    下例从百度网页上读取数据,然后逐行显示在屏幕上。

static void Main(string[] args)
{
    WebClient client = new WebClient();
    Stream strm = client.OpenRead("http://www.baidu.com/");
    StreamReader sr = new StreamReader(strm);
    string line;
    while ((line = sr.ReadLine()) != null)
        Console.WriteLine(line);
 
}

2.OpenWrite()

    OpenWrite()返回一个可写的数据流,便于用户写入数据。

    下例在工程目录下创建文件test.txt,然后写入内容"Hello World”。

static void Main(string[] args)
{
    WebClient client = new WebClient();
    Stream strm = client.OpenWrite("test.txt", "PUT");
    StreamWriter writer = new StreamWriter(strm);
    writer.WriteLine("Hello World");
    writer.Close();
}

3.DownloadFile()

   DownloadFile()用于下载文件。

   下例下载百度网页,保存在本地目录下的文件“File.htm”中

WebClient client = new WebClient();
client.DownloadFile("http://www.baidu.com/", "File.htm");

4.UploadFile()

   UploadFile()把文件上传到指定位置。

   下例将本地目录下文件“File.htm”上传到网站。

WebClient client = new WebClient();
client.UploadFile("http://www.example.com/", "File.htm");

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值