WebClient 用法总结

一、WebClient概述

   WebClient提供向 URI 标识的资源发送数据和从 URI 标识的资源接收数据的公共方法, WebClient 类提供向 URI 标识的任何本地、Intranet 或 Internet 资源发送数据以及从这些资源接收数据的公共方法。
   WebClient 类使用 WebRequest 类提供对资源的访问。WebClient 实例可以通过任何已向 WebRequest.RegisterPrefix 方法注册的 WebRequest 子代访问数据。默认情况下,WebClient 实例不发送可选的 HTTP 报头。
   如果您的请求需要可选报头,必须将该报头添加到 Headers 集合。例如,要在响应中保留查询,必须添加用户代理报头。此外,如果用户代理标头丢失,服务器可能返回 500(内部服务器错误)。
   在 WebClient 实例中,AllowAutoRedirect 设置为 true。
   

   查看MSND上对webclient的解释,有上传与下载方法:

WebClient提供一下上传方法:
   WebClient 用法总结_第1张图片
WebClient提供一下下载方法:

WebClient 用法总结_第2张图片

二、WebClient与其他网络相关类的区别

WebClient和HttpWebRequst是用来获取数据的2种方式,一般而言,WebClient更倾向于“按需下载”,事实上掌握它也是相对容易的,而HttpWebRequst则允许你设置请求头或者对内容需要更多的控制,
后者有点类似于form中的submit。虽然两者都是异步请求事件,但是WebClient是基于事件的异步,而HttpWebRequst是基于代理的异步编程。


三、WebClient使用范例

文件下载:

 protected void Button1_Click(object sender, EventArgs e)
        {
            String url = "http://localhost/SprayerWeb/download/1.zip";
            WebClient webclient = new WebClient();
            byte [] bytes = webclient.DownloadData(url);
            string path = string.Format("{0}\\{1}\\{2}{3}", Server.MapPath("~"), "download", DateTime.Now.ToString("yyyyHHmmHHmmssfff"), ".zip");
            FileStream fs = new FileStream(path, FileMode.Create);
            fs.Write(bytes, 0, bytes.Length);
            fs.Close();
        }

        protected void Button2_Click(object sender, EventArgs e)
        {
            WebClient webclient = new WebClient();
            String url = "http://localhost/SprayerWeb/download/1.zip";
            Stream stream = webclient.OpenRead(url);
             string path = string.Format("{0}\\{1}\\{2}{3}", Server.MapPath("~"), "download", DateTime.Now.ToString("yyyyHHmmHHmmssfff"), ".zip");
             FileStream fs = new FileStream(path, FileMode.Create);
             byte[] bytes = new byte[8192];
             int read = 0;
             while ((read = stream.Read(bytes, 0, bytes.Length)) > 0) {
                 fs.Write(bytes, 0, read);//这儿需要使用read,不能使用bytes.Length
             }
             fs.Close();
        }

        protected void Button3_Click(object sender, EventArgs e)
        {
            WebClient webclient = new WebClient();
            String url = "http://localhost/SprayerWeb/download/1.zip";
            string path = string.Format("{0}\\{1}\\{2}{3}", Server.MapPath("~"), "download", DateTime.Now.ToString("yyyyHHmmHHmmssfff"), ".zip");
            webclient.DownloadFile(url, path);
            
        }

        protected void Button4_Click(object sender, EventArgs e)
        {
            String url = "http://localhost/SprayerWeb/download/1.zip";
            Uri uri = new Uri(url, UriKind.Absolute);
            WebClient webclient = new WebClient();
            webclient.OpenReadAsync(uri);
            webclient.OpenReadCompleted+=webclient_OpenReadCompleted;
        }

        private void webclient_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
        {
            Stream stream = e.Result;
            byte[] bytes = new byte[8192];
            int read = 0;
            string path = string.Format("{0}\\{1}\\{2}{3}", Server.MapPath("~"), "download", DateTime.Now.ToString("yyyyHHmmHHmmssfff"), ".zip");
            FileStream fs = new FileStream(path, FileMode.Create);
            while ((read = stream.Read(bytes, 0, bytes.Length)) > 0) {
                fs.Write(bytes, 0, read);
            }
            fs.Close();
            stream.Close();

        }

文件上传:

 protected void Button5_Click(object sender, EventArgs e)
        {
            //在IIS6下没有执行成功,以后再调试吧
            WebClient webclient = new WebClient();
            string targetpath = string.Format("{0}{1}{2}","http://localhost/WebApp/upload/",DateTime.Now.ToString("yyyyMMddHHmmssfff"),".zip");
            
            string sourcepath = string.Format("{0}\\{1}\\{2}{3}", Server.MapPath("~"), "download", "1", ".zip");
            byte[] responseArray = webclient.UploadFile(targetpath, "PUT", sourcepath);
        }

        protected void Button6_Click(object sender, EventArgs e)
        {
            //在IIS6下没有执行成功,以后再调试吧
            string targetpath = string.Format("{0}{1}{2}", "http://localhost/WebApp/upload/", DateTime.Now.ToString("yyyyMMddHHmmssfff"), ".zip");
            string sourcepath = string.Format("{0}\\{1}\\{2}{3}", Server.MapPath("~"), "download", "1", ".zip");
            WebClient webclient = new WebClient();
            FileStream fs = new FileStream(sourcepath, FileMode.Open, FileAccess.Read);
            byte[] bt = new byte[fs.Length];
            fs.Read(bt, 0, bt.Length);
            byte[] responseArray = webclient.UploadData(targetpath, "PUT", bt);
            fs.Close();
        }

        protected void Button7_Click(object sender, EventArgs e)
        {
            WebClient webclient = new WebClient();
             string sourcepath = string.Format("{0}\\{1}\\{2}{3}", Server.MapPath("~"), "download", "1", ".zip");
            byte[] responseArray= webclient.UploadFile("http://localhost/WebApp/upload.aspx", "POST", sourcepath);
            Response.Write("result:"+System.Text.Encoding.UTF8.GetString(responseArray));
        }

upload.aspx文件代码如下:

 protected void Page_Load(object sender, EventArgs e)
        {
            //string uploadpath = string.Format("{0}\\{1}{}");

            foreach (string f in Request.Files.AllKeys)
            {
                HttpPostedFile postfile = Request.Files[f];
                string path = String.Format("{0}\\{1}\\{2}{3}",Server.MapPath("~"),"upload",DateTime.Now.Ticks.ToString(),".zip");
                postfile.SaveAs(path);
            }
            Response.Write("Success");
        }



更多详细内容参考:https://msdn.microsoft.com/zh-cn/library/system.net.webclient%28VS.80%29.aspx



你可能感兴趣的:(c#,WebClient,C#,文件下载,C#,文件上传)