C# 上傳文件的多種方法

 

方案一:

注意:要開啓虛擬目錄的“寫入”權限,要不然就報 403 錯誤

工作中用到winform上傳文件(-_-!,很少用winform,搞了半天)
碰到一點問題,解決如下
1、501 爲實現錯誤
解決方法:
先把IISWEB服務擴展中的WebDev打開
然後
IIS站點添加MIME  txt類型 常見的MIME類型如下
超文本標記語言文本 .html,.html text/html
普通文本 .txt text/plain
RTF文本 .rtf application/rtf
GIF圖形 .gif image/gif
JPEG圖形 .ipeg,.jpg image/jpeg
au聲音文件 .au audio/basic
MIDI音樂文件 mid,.midi audio/midi,audio/x-midi
RealAudio音樂文件 .ra, .ram audio/x-pn-realaudio
MPEG文件 .mpg,.mpeg video/mpeg
AVI文件 .avi video/x-msvideo
GZIP文件 .gz application/x-gzip
TAR文件 .tar application/x-tar
再然後
設置目標文件夾的可寫性

using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.IO;

namespace Common
{
/**//// <summary>
/// winform形式的文件傳輸類
/// </summary>
public class WinFileTransporter
{
/**//// <summary>
/// WebClient上傳文件至服務器,默認不自動改名
/// </summary>
/// <param name="fileNamePath">文件名,全路徑格式</param>
/// <param name="uriString">服務器文件夾路徑</param>
public void UpLoadFile(string fileNamePath, string uriString)
{
            UpLoadFile(fileNamePath, uriString, false);
        }
/**//// <summary>
/// WebClient上傳文件至服務器
/// </summary>
/// <param name="fileNamePath">文件名,全路徑格式</param>
/// <param name="uriString">服務器文件夾路徑</param>
/// <param name="IsAutoRename">是否自動按照時間重命名</param>
public void UpLoadFile(string fileNamePath, string uriString, bool IsAutoRename)
{
string fileName = fileNamePath.Substring(fileNamePath.LastIndexOf("\\") + 1);
string NewFileName = fileName;
if (IsAutoRename)
{
                NewFileName = DateTime.Now.ToString("yyMMddhhmmss") + DateTime.Now.Millisecond.ToString() + fileNamePath.Substring(fileNamePath.LastIndexOf("."));
            }

string fileNameExt = fileName.Substring(fileName.LastIndexOf(".") + 1);
if (uriString.EndsWith("/") == false) uriString = uriString + "/";

            uriString = uriString + NewFileName;
            Utility.LogWriter log = new Utility.LogWriter();
//log.AddLog(uriString, "Log");
//log.AddLog(fileNamePath, "Log");
/**//**/
/**//// 創建WebClient實例
            WebClient myWebClient = new WebClient();
            myWebClient.Credentials = CredentialCache.DefaultCredentials;
// 要上傳的文件
            FileStream fs = new FileStream(fileNamePath, FileMode.Open, FileAccess.Read);
//FileStream fs = OpenFile();
            BinaryReader r = new BinaryReader(fs);
byte[] postArray = r.ReadBytes((int)fs.Length);
            Stream postStream = myWebClient.OpenWrite(uriString, "PUT");


try
{

//使用UploadFile方法可以用下面的格式
//myWebClient.UploadFile(uriString,"PUT",fileNamePath);


if (postStream.CanWrite)
{
                    postStream.Write(postArray, 0, postArray.Length);
                    postStream.Close();
                    fs.Dispose();
                    log.AddLog("上傳日誌文件成功!", "Log");
                }
else
{
                    postStream.Close();
                    fs.Dispose();
                    log.AddLog("上傳日誌文件失敗,文件不可寫!", "Log");
                }

            }
catch (Exception err)
{
                postStream.Close();
                fs.Dispose();
//Utility.LogWriter log = new Utility.LogWriter();
                log.AddLog(err, "上傳日誌文件異常!", "Log");
throw err;
            }
finally
{
                postStream.Close();
                fs.Dispose();
            }
        }


/**//**/
/**//// <summary>
/// 下載服務器文件至客戶端

/// </summary>
/// <param name="URL">被下載的文件地址,絕對路徑</param>
/// <param name="Dir">另存放的目錄</param>
public void Download(string URL, string Dir)
{
            WebClient client = new WebClient();
string fileName = URL.Substring(URL.LastIndexOf("\\") + 1);  //被下載的文件名

string Path = Dir + fileName;   //另存爲的絕對路徑+文件名
            Utility.LogWriter log = new Utility.LogWriter();
try
{
                WebRequest myre = WebRequest.Create(URL);
            }
catch (Exception err)
{
//MessageBox.Show(exp.Message,"Error"); 
                log.AddLog(err, "下載日誌文件異常!", "Log");
            }

try
{
                client.DownloadFile(URL, fileName);
                FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);
                BinaryReader r = new BinaryReader(fs);
byte[] mbyte = r.ReadBytes((int)fs.Length);

                FileStream fstr = new FileStream(Path, FileMode.OpenOrCreate, FileAccess.Write);

                fstr.Write(mbyte, 0, (int)fs.Length);
                fstr.Close();

            }
catch (Exception err)
{
//MessageBox.Show(exp.Message,"Error");
                log.AddLog(err, "下載日誌文件異常!", "Log");
            }
        }

    }
}

方案二:

轉:http://blog.csdn.net/walkinhill/archive/2004/08/28/87656.aspx

相信用ASP.NET寫一個上傳文件的網頁,大家都會寫,但是有沒有人想過通過在WinForm中通過HTTP協議上傳文件呢?

有些人說要向服務器端上傳文件,用FTP協議不是很簡單嗎?效率又高,爲什麼還要使用HTTP協議那麼麻煩呢?這裏面有幾個原因:

(1)FTP服務器的部署相對麻煩,還要設置權限,權限設置不對,還會惹來一系列的安全問題。

(2)如果雙方都還有防火牆,又不想開發FTP相關的一些端口時,HTTP就會大派用場,就像WEB Services能穿透防火牆一樣。

(3)其他的...,還在想呢...

但是使用HTTP也有他的一些問題,例如不能斷點續傳,大文件上傳很難,速度很慢,所以HTTP協議上傳的文件大小不應該太大。

說了這麼多,原歸正傳,一般來說,在Winform裏通過HTTP上傳文件有幾種可選的方法:

(1)前面提到的Web Services,就是一種很好的方法,通過編寫一個WebMethod,包含有 byte[] 類型的參數,然後調用Web Services的方法,文件內容就會以Base64編碼傳到服務器上,然後重新保存即可。

[WebMethod]
public void UploadFile(byte[] content,string filename){
           Stream sw = new StreamWriter(...);
           sw.Close();
}
當然,這種通過Base64編碼的方法效率比較低,那麼可以採用WSE,支持附件,並以2進制形式傳送,效率會更高。
(2)除了通過WebService,另外一種更簡單的方法就是通過WebClient或者HttpWebRequest來模擬HTTP的POST動作來實現。這時候首先需要編寫一個asp.net web form來響應上傳,代碼如下:
<%@ Page language="c#" Codebehind="WebForm1.aspx.cs" AutoEventWireup="false" Inherits="UploadFileWeb.WebForm1" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<html>
<head>
  <title>WebForm1</title>
  <meta name="GENERATOR" Content="Microsoft Visual Studio .NET 7.1">
  <meta name="CODE_LANGUAGE" Content="C#">
  <meta name="vs_defaultClientScript" content="JavaScript">
  <meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5">
</head>
<body>
  <form id="Form1" method="post" runat="server">
  </form>
</body>
</html>

using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;

namespace UploadFileWeb
{
/// <summary>
/// WebForm1 的摘要說明。
/// </summary>
public class WebForm1 : System.Web.UI.Page
{
  private void Page_Load(object sender, System.EventArgs e)
  {
   // 在此處放置用戶代碼以初始化頁面
   foreach( string f in Request.Files.AllKeys)
   {
    HttpPostedFile file = Request.Files[f];
    file.SaveAs(@"D:\Temp\" + file.FileName);
   }
   if( Request.Params["testKey"] != null )
   {
    Response.Write(Request.Params["testKey"]);
   }
  }

  #region Web 窗體設計器生成的代碼
  override protected void OnInit(EventArgs e)
  {
   //
   // CODEGEN: 該調用是 ASP.NET Web 窗體設計器所必需的。
   //
   InitializeComponent();
   base.OnInit(e);
  }
  /// <summary>
  /// 設計器支持所需的方法 - 不要使用代碼編輯器修改
  /// 此方法的內容。
  /// </summary>
  private void InitializeComponent()
  {   
   this.Load += new System.EventHandler(this.Page_Load);
  }
  #endregion
}
}

其實這個頁面跟我們平常寫的asp.net上傳文件代碼是一樣的,在Web 頁的Request對象中包含有Files這個對象,裏面就包含了通過POST方式上傳的所有文件的信息,這時所需要做的就是調用 Request.Files[i].SaveAs方法。

但是怎麼讓才能在WinForm裏面模擬想Web Form POST 數據呢?System.Net命名空間裏面提供了兩個非常有用的類,一個是WebClient,另外一個是HttpWebRequest類。如果我們不需要通過代理服務器來上傳文件,那麼非常簡單,只需要簡單的調用WebClient.UploadFile方法就能實現上傳文件:
private void button1_Click(object sender, System.EventArgs e)
  {
   WebClient myWebClient = new WebClient();
   myWebClient.UploadFile("http://localhost/UploadFileWeb/WebForm1.aspx","POST",@"D:\Temp\Java\JavaStart\JavaStart2.exe");
       }

是不是覺得很簡單呢?確實就這麼簡單。

但是如果要通過代理服務器上傳又怎麼辦呢?那就需要使用到HttpWebRequest,但是該類沒有Upload方法,但是幸運的是我們通過Reflector反編譯了WebClient.UploadFile方法後,我們發現其內部也是通過WebRequest來實現的,代碼如下:
public byte[] UploadFile(string address, string method, string fileName)
{
      string text1;
      string text2;
      WebRequest request1;
      string text3;
      byte[] buffer1;
      byte[] buffer2;
      long num1;
      byte[] buffer3;
      int num2;
      WebResponse response1;
      byte[] buffer4;
      DateTime time1;
      long num3;
      string[] textArray1;
      FileStream stream1 = null;
      try
      {
            fileName = Path.GetFullPath(fileName);
            time1 = DateTime.Now;
            num3 = time1.Ticks;
            text1 = "---------------------" + num3.ToString("x");
            if (this.m_headers == null)
            {
                  this.m_headers = new WebHeaderCollection();
            }
            text2 = this.m_headers["Content-Type"];
            if (text2 != null)
            {
                  if (text2.ToLower(CultureInfo.InvariantCulture).StartsWith("multipart/"))
                  {
                        throw new WebException(SR.GetString("net_webclient_Multipart"));
                  }
            }
            else
            {
                  text2 = "application/octet-stream";
            }
            this.m_headers["Content-Type"] = "multipart/form-data; boundary=" + text1;
            this.m_responseHeaders = null;
            stream1 = new FileStream(fileName, FileMode.Open, FileAccess.Read);
            request1 = WebRequest.Create(this.GetUri(address));
            request1.Credentials = this.Credentials;
            this.CopyHeadersTo(request1);
            request1.Method = method;
            textArray1 = new string[7];
            textArray1[0] = "--";
            textArray1[1] = text1;
            textArray1[2] = "\r\nContent-Disposition: form-data; name=\"file\"; filename=\"";
            textArray1[3] = Path.GetFileName(fileName);
            textArray1[4] = "\"\r\nContent-Type: ";
            textArray1[5] = text2;
            textArray1[6] = "\r\n\r\n";
            text3 = string.Concat(textArray1);
            buffer1 = Encoding.UTF8.GetBytes(text3);
            buffer2 = Encoding.ASCII.GetBytes("\r\n--" + text1 + "\r\n");
            num1 = 9223372036854775807;
            try
            {
                  num1 = stream1.Length;
                  request1.ContentLength = ((num1 + ((long) buffer1.Length)) + ((long) buffer2.Length));
            }
            catch
            {
            }
            buffer3 = new byte[Math.Min(((int) 8192), ((int) num1))];
            using (Stream stream2 = request1.GetRequestStream())
            {
                  stream2.Write(buffer1, 0, buffer1.Length);
                  do
                  {
                        num2 = stream1.Read(buffer3, 0, buffer3.Length);
                        if (num2 != 0)
                        {
                              stream2.Write(buffer3, 0, num2);
                        }
                  }
                  while ((num2 != 0));
                  stream2.Write(buffer2, 0, buffer2.Length);
            }
            stream1.Close();
            stream1 = null;
            response1 = request1.GetResponse();
            this.m_responseHeaders = response1.Headers;
            return this.ResponseAsBytes(response1);
      }
      catch (Exception exception1)
      {
            if (stream1 != null)
            {
                  stream1.Close();
                  stream1 = null;
            }
            if ((exception1 is WebException) || (exception1 is SecurityException))
            {
                  throw;
            }
            throw new WebException(SR.GetString("net_webclient"), exception1);
      }
      return buffer4;
}
在這段代碼裏面其實最關鍵的就是如何模擬POST請求,通過分析代碼和監視HTTP,我們可以發現模擬的POST格式如下:
-----------------------8c64f47716481f0  //時間戳

Content-Disposition: form-data; name="file"; filename="a.txt"  //文件名

Content-Type: application/octet-stream

//文件的內容

-----------------------8c64f47716481f0

這時候,我們只需自己編碼來模擬這麼一組數據就行(我們還可以好好借鑑MS的代碼呢),以下就是代碼(聲明一下,我是借用了別人的代碼)
public class wwHttp
{

  /// <summary>
  /// Fires progress events when using GetUrlEvents() to retrieve a URL.
  /// </summary>
  public event OnReceiveDataHandler OnReceiveData;

  /// <summary>
  /// Determines how data is POSTed when cPostBuffer is set.
  /// 1 - UrlEncoded
  /// 2 - Multi-Part form vars
  /// 4 - XML (raw buffer content type: text/xml)
  /// </summary>
  public int PostMode
  {
   get { return this.nPostMode; }
   set { this.nPostMode = value; }
  }

  /// <summary>
  ///  User name used for Authentication.
  ///  To use the currently logged in user when accessing an NTLM resource you can use "AUTOLOGIN".
  /// </summary>
  public string Username
  {
   get { return this.cUsername; }
   set { cUsername = value; }
  }

  /// <summary>
  /// Password for Authentication.
  /// </summary>
  public string Password
  {
   get {return this.cPassword;}
   set {this.cPassword = value;}
  }

  /// <summary>
  /// Address of the Proxy Server to be used.
  /// Use optional DEFAULTPROXY value to specify that you want to IE's Proxy Settings
  /// </summary>
  public string ProxyAddress  
  {
   get {return this.cProxyAddress;}
   set {this.cProxyAddress = value;}
  }

  /// <summary>
  /// Semicolon separated Address list of the servers the proxy is not used for.
  /// </summary>
  public string ProxyBypass
  {
   get {return this.cProxyBypass;}
   set {this.cProxyBypass = value;}
  }

  /// <summary>
  /// Username for a password validating Proxy. Only used if the proxy info is set.
  /// </summary>
  public string ProxyUsername
  {
   get {return this.cProxyUsername;}
   set {this.cProxyUsername = value;}
  }
  /// <summary>
  /// Password for a password validating Proxy. Only used if the proxy info is set.
  /// </summary>
  public string ProxyPassword
  {
   get {return this.cProxyPassword;}
   set {this.cProxyPassword = value;}
  }

  /// <summary>
  /// Timeout for the Web request in seconds. Times out on connection, read and send operations.
  /// Default is 30 seconds.
  /// </summary>
  public int Timeout
  {
   get {return this.nConnectTimeout; }
   set {this.nConnectTimeout = value; }
  }

  /// <summary>
  /// Error Message if the Error Flag is set or an error value is returned from a method.
  /// </summary>
  public string ErrorMsg
  {
   get { return this.cErrorMsg; }
   set { this.cErrorMsg = value; }
  }
  /// <summary>
  /// Error flag if an error occurred.
  /// </summary>
  public bool Error
  {
   get { return this.bError; }
   set { this.bError = value; }
  }

  /// <summary>
  /// Determines whether errors cause exceptions to be thrown. By default errors
  /// are handled in the class and the Error property is set for error conditions.
  /// (not implemented at this time).
  /// </summary>
  public bool ThrowExceptions
  {
   get { return bThrowExceptions; }
   set { this.bThrowExceptions = value;}
  }

  /// <summary>
  /// If set to a non-zero value will automatically track cookies. The number assigned is the cookie count.
  /// </summary>
  public bool HandleCookies
  {
   get { return this.bHandleCookies; }
   set { this.bHandleCookies = value; }
  }
  public CookieCollection Cookies {
   get { return this.oCookies; }
   set { this.Cookies = value; }
  }
  public HttpWebResponse WebResponse  {
   get { return this.oWebResponse;}
   set { this.oWebResponse = value; }
  }
  public HttpWebRequest WebRequest  {
   get { return this.oWebRequest; }
   set { this.oWebRequest = value; }
  }

  // *** member properties
  //string cPostBuffer = "";
  MemoryStream oPostStream;
  BinaryWriter oPostData;

  int nPostMode = 1;

  int nConnectTimeout = 30;
  string cUserAgent = "West Wind HTTP .NET";

  string cUsername = "";
  string cPassword = "";

  string cProxyAddress = "";
  string cProxyBypass = "";
  string cProxyUsername = "";
  string cProxyPassword = "";

  bool bThrowExceptions = false;
  bool bHandleCookies = false;
  string cErrorMsg = "";
  bool bError = false;
  HttpWebResponse oWebResponse;
  HttpWebRequest oWebRequest;
  CookieCollection oCookies;

  string cMultiPartBoundary = "-----------------------------7cf2a327f01ae";

  public void wwHTTP()
  {
   //
   // TODO: Add constructor logic here
   //

  }

  /// <summary>
  /// Adds POST form variables to the request buffer.
  /// HttpPostMode determines how parms are handled.
  /// 1 - UrlEncoded Form Variables. Uses key and value pairs (ie. "Name","Rick") to create URLEncoded content
  /// 2 - Multi-Part Forms - not supported
  /// 4 - XML block - Post a single XML block. Pass in as Key (1st Parm)
  /// other - raw content buffer. Just assign to Key.
  /// </summary>
  /// <param name="Key">Key value or raw buffer depending on post type</param>
  /// <param name="Value">Value to store. Used only in key/value pair modes</param>
  public void AddPostKey(string Key, byte[] Value)
  {
   if (this.oPostData == null)
   {
    this.oPostStream = new MemoryStream();
    this.oPostData = new BinaryWriter(this.oPostStream);
   }
   if (Key == "RESET")
   {
    this.oPostStream = new MemoryStream();
    this.oPostData = new BinaryWriter(this.oPostStream);
   }

   switch(this.nPostMode)
   {
    case 1:
     this.oPostData.Write(Encoding.GetEncoding(1252).GetBytes(
          Key + "=" + System.Web.HttpUtility.UrlEncode(Value) + "&"));
     break;
    case 2:
     this.oPostData.Write( Encoding.GetEncoding(1252).GetBytes(
      "--" + this.cMultiPartBoundary + "\r\n" +
      "Content-Disposition: form-data; name=\"" +Key+"\"\r\n\r\n") );
     this.oPostData.Write( Value );

     this.oPostData.Write( Encoding.GetEncoding(1252).GetBytes("\r\n") );
     break;
    default:
     this.oPostData.Write( Value );
     break;
   }
  }

  public void AddPostKey(string Key, string Value)
  {
   this.AddPostKey(Key,Encoding.GetEncoding(1252).GetBytes(Value));
  }

  /// <summary>
  /// Adds a fully self contained POST buffer to the request.
  /// Works for XML or previously encoded content.
  /// </summary>
  /// <param name="PostBuffer"></param>
  public void AddPostKey(string FullPostBuffer)
  {
   this.oPostData.Write( Encoding.GetEncoding(1252).GetBytes(FullPostBuffer) );
  }

  public bool AddPostFile(string Key,string FileName)
  {
   byte[] lcFile;

   if (this.nPostMode != 2) {
    this.cErrorMsg = "File upload allowed only with Multi-part forms";
    this.bError = true;
    return false;
   }

   try
   {   
    FileStream loFile = new FileStream(FileName,System.IO.FileMode.Open,System.IO.FileAccess.Read);

    lcFile = new byte[loFile.Length];
    loFile.Read(lcFile,0,(int) loFile.Length);
    loFile.Close();
   }
   catch(Exception e)
   {
    this.cErrorMsg = e.Message;
    this.bError = true;
    return false;
   }

   this.oPostData.Write( Encoding.GetEncoding(1252).GetBytes(
     "--" + this.cMultiPartBoundary + "\r\n"  +
     "Content-Disposition: form-data; name=\"" + Key + "\" filename=\"" +
     new FileInfo(FileName).Name + "\"\r\n\r\n") );

   this.oPostData.Write( lcFile );

   this.oPostData.Write( Encoding.GetEncoding(1252).GetBytes("\r\n")) ;

   return true;
  }

  /// <summary>
  /// Return a the result from an HTTP Url into a StreamReader.
  /// Client code should call Close() on the returned object when done reading.
  /// </summary>
  /// <param name="Url">Url to retrieve.</param>
  /// <param name="WebRequest">An HttpWebRequest object that can be passed in with properties preset.</param>
  /// <returns></returns>
  protected StreamReader GetUrlStream(string Url,HttpWebRequest Request)
  {
   try
   {
    this.bError = false;
    this.cErrorMsg = "";

    if (Request == null)
    {
     Request =  (HttpWebRequest) System.Net.WebRequest.Create(Url);
    }
    Request.UserAgent = this.cUserAgent;
    Request.Timeout = this.nConnectTimeout * 1000;

    // *** Save for external access
    this.oWebRequest = Request;

    // *** Handle Security for the request
    if (this.cUsername.Length > 0)
    {
     if (this.cUsername=="AUTOLOGIN")
      Request.Credentials = CredentialCache.DefaultCredentials;
     else
      Request.Credentials = new NetworkCredential(this.cUsername,this.cPassword);
    }

    // *** Handle Proxy Server configuration
    if (this.cProxyAddress.Length > 0)
    {
     if (this.cProxyAddress == "DEFAULTPROXY")
     {
      Request.Proxy = new WebProxy();
      Request.Proxy = WebProxy.GetDefaultProxy();
     }
     else
     {
      WebProxy loProxy = new WebProxy(this.cProxyAddress,true);
      if (this.cProxyBypass.Length > 0)
      {
       loProxy.BypassList = this.cProxyBypass.Split(';');
      }

      if (this.cProxyUsername.Length > 0)
       loProxy.Credentials = new NetworkCredential(this.cProxyUsername,this.cProxyPassword);

      Request.Proxy = loProxy;
     }
    }
    // *** Handle cookies - automatically re-assign
    if (this.bHandleCookies)
    {
     Request.CookieContainer = new CookieContainer();
     if (this.oCookies != null && this.oCookies.Count > 0)
     {
      Request.CookieContainer.Add(this.oCookies);
     }
    }

    // *** Deal with the POST buffer if any
    if (this.oPostData != null)
    {
     Request.Method = "POST";
     switch (this.nPostMode)
     {
      case 1:
       Request.ContentType = "application/x-www-form-urlencoded";
       // strip off any trailing & which can cause problems with some
       // http servers
//       if (this.cPostBuffer.EndsWith("&"))
//        this.cPostBuffer = this.cPostBuffer.Substring(0,this.cPostBuffer.Length-1);
       break;
      case 2:
       Request.ContentType = "multipart/form-data; boundary=" + this.cMultiPartBoundary;
       this.oPostData.Write( Encoding.GetEncoding(1252).GetBytes( "--" + this.cMultiPartBoundary + "\r\n" ) );
       break;
      case 4:
       Request.ContentType = "text/xml";
       break;
      default:
       goto case 1;
     }

     Stream loPostData = Request.GetRequestStream();
     //loPostData.Write(lcPostData,0,lcPostData.Length);
     this.oPostStream.WriteTo(loPostData);   
     byte[] buffer = new byte[this.oPostStream.Length];
     buffer = this.oPostStream.ToArray();
     Console.Write(Encoding.GetEncoding(1252).GetString(buffer,0,buffer.Length));

     //*** Close the memory stream
     this.oPostStream.Close();
     this.oPostStream = null;

     //*** Close the Binary Writer
     this.oPostData.Close();
     this.oPostData = null;

     //*** Close Request Stream
     loPostData.Close();

     // *** clear the POST buffer
     //this.cPostBuffer = "";
    }
    // *** Retrieve the response headers
    HttpWebResponse Response = (HttpWebResponse) Request.GetResponse();

    // ** Save cookies the server sends
    if (this.bHandleCookies) 
    {
     if (Response.Cookies.Count > 0) 
     {
      if (this.oCookies == null) 
      {
       this.oCookies = Response.Cookies;
      }
      else
      {
       // ** If we already have cookies update the list
       foreach (Cookie oRespCookie in Response.Cookies) 
       {
        bool bMatch = false;
        foreach(Cookie oReqCookie in this.oCookies) 
        {
         if (oReqCookie.Name == oRespCookie.Name) 
         {
          oReqCookie.Value = oRespCookie.Name;
          bMatch = true;
          break; //
         }
        } // for each ReqCookies
        if (!bMatch)
         this.oCookies.Add(oRespCookie);
       } // for each Response.Cookies
      }  // this.Cookies == null
     } // if Response.Cookie.Count > 0
    }  // if this.bHandleCookies = 0

    // *** Save the response object for external access
    this.oWebResponse = Response;

    Encoding enc;
    try
    {
     if (Response.ContentEncoding.Length  > 0)
      enc = Encoding.GetEncoding(Response.ContentEncoding);
     else
      enc = Encoding.GetEncoding(1252);
    }
    catch
    {
     // *** Invalid encoding passed
     enc = Encoding.GetEncoding(1252);
    }
    // *** drag to a stream
    StreamReader strResponse =
     new StreamReader(Response.GetResponseStream(),enc);
    return strResponse;
   }
   catch(Exception e)
   {
    if (this.bThrowExceptions)
     throw e;

    this.cErrorMsg = e.Message;
    this.bError = true;
    return null;
   }
  }

  /// <summary>
  /// Return a the result from an HTTP Url into a StreamReader.
  /// Client code should call Close() on the returned object when done reading.
  /// </summary>
  /// <param name="Url">Url to retrieve.</param>
  /// <returns></returns>
  public StreamReader GetUrlStream(string Url)
  {
   HttpWebRequest oHttpWebRequest = null;
   return this.GetUrlStream(Url,oHttpWebRequest);
  }

  /// <summary>
  /// Return a the result from an HTTP Url into a StreamReader.
  /// Client code should call Close() on the returned object when done reading.
  /// </summary>
  /// <param name="Request">A Request object</param>
  /// <returns></returns>
  public StreamReader GetUrlStream(HttpWebRequest Request)
  {
   return this.GetUrlStream(Request.RequestUri.AbsoluteUri,Request);
  }

  /// <summary>
  /// Return a the result from an HTTP Url into a string.
  /// </summary>
  /// <param name="Url">Url to retrieve.</param>
  /// <returns></returns>
  public string GetUrl(string Url)
  {
   StreamReader oHttpResponse = this.GetUrlStream(Url);
   if (oHttpResponse == null)
    return "";

   string lcResult = oHttpResponse.ReadToEnd();
   oHttpResponse.Close();

   return lcResult;
  }

  /// <summary>
  /// Return a the result from an HTTP Url into a string.
  /// </summary>
  /// <param name="Url">Url to retrieve.</param>
  /// <returns></returns>
  public byte[] GetUrlBytes(string Url)
  {
   StreamReader oHttpResponse = this.GetUrlStream(Url);
   if (oHttpResponse == null)
   {
    return null;
   }

   string lcResult = oHttpResponse.ReadToEnd();
   oHttpResponse.Close();

   return null;
  }

  /// <summary>
  /// Retrieves URL with events in the OnReceiveData event.
  /// </summary>
  /// <param name="Url"></param>
  /// <param name="BufferSize"></param>
  /// <returns></returns>
  public string GetUrlEvents(string Url,long BufferSize)
  {
   StreamReader oHttpResponse = this.GetUrlStream(Url);
   if (oHttpResponse == null)
    return "";

   long lnSize = BufferSize;
   if (this.oWebResponse.ContentLength > 0)
    lnSize = this.oWebResponse.ContentLength;
   else
    lnSize = 0;

   Encoding enc = Encoding.GetEncoding(1252);

   StringBuilder loWriter = new StringBuilder((int) lnSize);
   char[] lcTemp = new char[BufferSize];

   OnReceiveDataEventArgs oArgs = new OnReceiveDataEventArgs();
   oArgs.TotalBytes = lnSize;

   lnSize = 1;
   int lnCount = 0;
   long lnTotalBytes = 0;

   while (lnSize > 0)
   {
    lnSize = oHttpResponse.Read(lcTemp,0,(int) BufferSize);
    if (lnSize > 0)
    {
     loWriter.Append( lcTemp,0,(int) lnSize );
     lnCount++;
     lnTotalBytes += lnSize;

     // *** Raise an event if hooked up
     if (this.OnReceiveData != null)
     {
      /// *** Update the event handler
      oArgs.CurrentByteCount = lnTotalBytes;
      oArgs.NumberOfReads = lnCount;
      oArgs.CurrentChunk = lcTemp;
      this.OnReceiveData(this,oArgs);

      // *** Check for cancelled flag
      if (oArgs.Cancel)
       goto CloseDown;
     }
    }
   } // while

  CloseDown:
   oHttpResponse.Close();

   // *** Send Done notification
   if (this.OnReceiveData != null && !oArgs.Cancel)
   {
    // *** Update the event handler
    oArgs.Done = true;
    this.OnReceiveData(this,oArgs);
   }

//   return lcHtml;
   return loWriter.ToString();
  }

  public delegate void OnReceiveDataHandler(object sender, OnReceiveDataEventArgs e);
  public class OnReceiveDataEventArgs
  {
   public long CurrentByteCount=0;
   public long TotalBytes = 0;
   public int NumberOfReads = 0;
   public char[] CurrentChunk;
   public bool Done = false;
   public bool Cancel = false;
  }  
}

在wwHttp這個類裏面,不僅僅可以傳送文件AddPostFile方法,還可以傳送變量AddPostKey方法。
這樣,如果我們要通過代理服務器傳送文件,就可以編寫如下的代碼了:
wwHttp ww = new wwHttp();
   ww.ProxyAddress = "202.132.156.124";   
   ww.PostMode = 2;
   ww.AddPostKey("testKey","test");
   ww.AddPostFile("myfile",@"D:\Temp\Java\JavaStart\JavaStart2.jar");  
   string shtml = ww.GetUrlEvents("http://localhost/UploadFileWeb/WebForm1.aspx",409600);
   Console.Write(shtml);
小結:

(1)通過Web Services傳文件。

(2)如果不需要使用代理,使用WebClient類

(3)如果需要使用代理,使用擴展得到的類wwHttp

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章