WebClient 类的使用和下载文件

来源:互联网 发布:淘宝专门领券的网站 编辑:程序博客网 时间:2024/05/16 10:55

WebClient 类提供向URI标识的任何本地、Intranet或Internet资源发送数据及用这些资源接收数据的方法。
也就是说,它更多用在下载文件用的

    //实例化WebClient对象            WebClient client = new WebClient();            client.BaseAddress = "http://www.mrwxk.com";                    //设置WebClient的基URI            client.Encoding = Encoding.UTF8;                                //指定下载字符串的编码格式            //为WebClient类对象添加报头            client.Headers.Add("Content-Type","application/x-www-form-urlencoded");            //使用OperRead方法获取指定网站的数据,并保存到Stream中            Stream stream = client.OpenRead("http://www.mrwxk.com");            StreamReader sreader = new StreamReader(stream);            string str = string.Empty;            while ((str=sreader.ReadLine())!=null)            {                Console.WriteLine(str);            }            //调用WebClient对象的DownLoadFile方法将指定的网站内容保存到 D  盘中并创建一个新的txt文件            client.DownloadFile("http://www.mrwxk.com","D:\\"+DateTime.Now.ToFileTime()+".txt");            Console.WriteLine("保存成功");            Console.ReadLine();

控制台显示:

这里写图片描述

D盘里保存数据显示这里写图片描述

保存到D盘中

0 0
原创粉丝点击