C# WebClient 的文件上传下载

 上传文件

 

   string path = openFileDialog1.FileName;
                WebClient wc = new WebClient();
                wc.Credentials = CredentialCache.DefaultCredentials;
                wc.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
                wc.QueryString["fname"] = openFileDialog1.SafeFileName;
                byte[] fileb = wc.UploadFile(new Uri(@"http://192.168.31.37:8977/FileHandler.ashx"), "POST", path);
                string res = Encoding.GetEncoding("gb2312").GetString(fileb);

                  //或者
                //wc.UploadFileAsync(new Uri(@"http://192.168.31.37:8977/FileHandler.ashx"), "POST", path);
                //wc.UploadFileCompleted += (s, es) =>
                //{
                //    MessageBox.Show(Encoding.GetEncoding("gb2312").GetString(es.Result));
                //};
        

 服务端处理请求

 public class FileHandler : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            try
            { 
            HttpFileCollection files = context.Request.Files;
            if (files.Count > 0)
            {
                files[0].SaveAs(HttpContext.Current.Server.MapPath("files/" + context.Request.QueryString["fname"]));
                context.Response.Write("save success!");
            }
            else
                context.Response.Write("hello request!");
            }
            catch (Exception ex)
            {
                context.Response.Write("save error!" + ex.Message);
            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }

下载文件

  if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
            {
                string path = folderBrowserDialog1.SelectedPath;
                WebClient wc = new WebClient();
                //wc.Credentials = CredentialCache.DefaultCredentials;
                wc.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
                string fileUrl = @"http://192.168.31.37:8977/files/多用文本.txt";

                wc.DownloadFile(new Uri(fileUrl), string.Format(@"{0}\{1}", path, fileUrl.Substring(fileUrl.LastIndexOf('/') + 1)));
                //或者
                wc.DownloadFileCompleted += (s, es) =>
                 {
                     MessageBox.Show("下载成功!");
                 };

                wc.DownloadFileAsync(new Uri(fileUrl), string.Format(@"{0}\{1}", path, fileUrl.Substring(fileUrl.LastIndexOf('/') + 1)));
            }

 

posted @ 2016-12-14 14:44  指间的徘徊  阅读(8684)  评论(4编辑  收藏  举报