使用WebClient进行文件上传

注释部分为异步上传,几行代码就能搞定

 public static bool Upload(string url, string path)
        {
            using (WebClient client = new WebClient())
            {
                try
                { 
                    //同步上传不容易报错
                    byte[] data = client.UploadFile(new Uri(url), "POST", path);
                    string reply = Encoding.UTF8.GetString(data);


                    return true;
                    //client.UploadFileAsync(new Uri(url), "POST", path);
                    //client.UploadFileCompleted += delegate(object sender, UploadFileCompletedEventArgs e)
                    //{
                    //    byte[] data = (byte[])e.Result;
                    //    string reply = Encoding.UTF8.GetString(data);
//};
                }
                catch (Exception e)
                {
                    return false;
                    throw new Exception("文件上传失败:" + e.Message + " " + path);
                }
            }
        }
原文地址:https://www.cnblogs.com/jhlong/p/7417157.html