1:上傳文件實例
public void UploadXMLLog(string xmlpath) { NameValueCollection nvc = new NameValueCollection(); CookieContainer cookies = new CookieContainer(); nvc.Add("", “”); ...... string url = "UrlPath"; string res = UploadFile(xmlpath, url, nvc, cookies); }
2:UploadFile源碼

1 public string UploadFile(string uploadfile, string url, NameValueCollection querystring, CookieContainer cookies, string fileFormName = "file", string contenttype = "multipart/form-data") 2 { 3 if ((fileFormName == null) || 4 (fileFormName.Length == 0)) 5 { 6 fileFormName = "file"; 7 } 8 9 if ((contenttype == null) || 10 (contenttype.Length == 0)) 11 { 12 contenttype = "application/octet-stream"; 13 } 14 Uri uri = new Uri(url); 15 string boundary = "----------" + DateTime.Now.Ticks.ToString("x"); 16 HttpWebRequest webrequest = (HttpWebRequest)WebRequest.Create(uri); 17 webrequest.CookieContainer = cookies; 18 webrequest.ContentType = "multipart/form-data; boundary=" + boundary; 19 webrequest.Method = "POST"; 20 StringBuilder sb = new StringBuilder(); 21 sb.Append("--"); 22 sb.Append(boundary); 23 sb.Append("\r\n"); 24 sb.Append("Content-Disposition: form-data; name=\""); 25 sb.Append(fileFormName); 26 sb.Append("\"; filename=\""); 27 sb.Append(uploadfile); 28 sb.Append("\""); 29 sb.Append("\r\n"); 30 sb.Append("Content-Type: "); 31 sb.Append(contenttype); 32 sb.Append("\r\n"); 33 sb.Append("\r\n"); 34 35 string postHeader = sb.ToString(); 36 byte[] postHeaderBytes = Encoding.UTF8.GetBytes(postHeader); 37 byte[] boundaryBytes = Encoding.ASCII.GetBytes("--" + boundary + "\r\n"); 38 byte[] br = Encoding.ASCII.GetBytes("\r\n"); 39 FileStream fileStream = new FileStream(uploadfile, FileMode.Open, FileAccess.Read); 40 long length = postHeaderBytes.Length + fileStream.Length + br.Length; 41 if (querystring != null) 42 { 43 44 StringBuilder sub = new StringBuilder(); 45 foreach (string key in querystring.Keys) 46 { 47 sub.Append("--"); 48 sub.Append(boundary); 49 sub.Append("\r\n"); 50 sub.Append("Content-Disposition: form-data; name=\""); 51 sub.Append(key); 52 sub.Append("\""); 53 sub.Append("\r\n"); 54 sub.Append("\r\n"); 55 sub.Append(querystring[key]); 56 sub.Append("\r\n"); 57 byte[] formitembytes = Encoding.UTF8.GetBytes(sub.ToString()); 58 length += formitembytes.Length; 59 } 60 } 61 length += boundaryBytes.Length; 62 webrequest.ContentLength = length; 63 Stream requestStream = webrequest.GetRequestStream(); 64 // Write out our post header 65 requestStream.Write(postHeaderBytes, 0, postHeaderBytes.Length); 66 67 // Write out the file contents 68 byte[] buffer = new Byte[checked((