功能:从特定的URI请求文件(.Net FrameWork目前支持http:、https:和file:标识符开头的URI)。

特点:功能比较简单。

用法:

1、使用WebClient下载文件。

范例一:使用WebClient下载文件,并保存到硬盘上(需要引入System.Net命名空间)。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
 
namespace Test
{
    class Program
    {
        static void Main(string[] args)
        {
            WebClient client = new WebClient();
            client.DownloadFile(new Uri("http://www.baidu.com/"), "d://webClient.html");
        }
    }
}
 
 

范例二;使用OpenRead()方法返回一个Stream引用。然后把数据提取到内存中(也可调用OpenWrite方法返回一个可写数据流不在演示)。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
 
namespace Test
{
    class Program
    {
        static void Main(string[] args)
        {
            WebClient client = new WebClient();
            using (Stream sw = client.OpenRead("http://www.baidu.com/"))
            {
                using (StreamReader sr = new StreamReader(sw))
                {
                    while (sr.ReadLine() != null)
                    {
                        Console.WriteLine(sr.ReadLine());
                        Console.ReadKey();
                    }
                }
            }
        }
    }
}
 
 

2、使用WebClient上传文件。

可以使用UpLoadFile函数和UpLoadData函数分别上传文件二进制数据。

但是WebClient不能提供身份验证证书,许多站点都不接受没有身份认证的验证证书。

相关文章:

  • 2022-12-23
  • 2021-11-03
  • 2021-12-23
  • 2022-01-07
  • 2021-11-13
  • 2021-12-14
  • 2021-12-06
  • 2021-09-25
猜你喜欢
  • 2021-05-22
  • 2021-09-04
  • 2021-06-17
  • 2021-11-02
相关资源
相似解决方案