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");

猜你喜欢

转载自blog.csdn.net/liyazhen2011/article/details/83657807
今日推荐