2013-01-23 36 views
1

我有一個要求,我必須從服務器根據輸入參數使用c#下載zip文件(大小可以在10mb - 400mb之間變化)。例如,下載userId = 10和year = 2012的報告。
網絡服務器接受這兩個參數並返回一個zip文件。我怎樣才能使用WebClient類來實現這一目標?
感謝C#根據輸入參數從url下載zip文件

+6

你到目前爲止試過了什麼? –

+0

對於這個尺寸,我會使用httpwebrequest /套接字來實現像下載恢復功能 – Tearsdontfalls

+4

Stackoverflow不是'給我teh codez'類型的網站。當你遇到問題時,你需要做自己的研究並提出一個問題。 – dandan78

回答

7

您可以通過擴展WebClient類

class ExtWebClient : WebClient 
    { 

     public NameValueCollection PostParam { get; set; } 

     protected override WebRequest GetWebRequest(Uri address) 
     { 
      WebRequest tmprequest = base.GetWebRequest(address); 

      HttpWebRequest request = tmprequest as HttpWebRequest; 

      if (request != null && PostParam != null && PostParam.Count > 0) 
      { 
       StringBuilder postBuilder = new StringBuilder(); 
       request.Method = "POST"; 
       //build the post string 

       for (int i = 0; i < PostParam.Count; i++) 
       { 
        postBuilder.AppendFormat("{0}={1}", Uri.EscapeDataString(PostParam.GetKey(i)), 
              Uri.EscapeDataString(PostParam.Get(i))); 
        if (i < PostParam.Count - 1) 
        { 
         postBuilder.Append("&"); 
        } 
       } 
       byte[] postBytes = Encoding.ASCII.GetBytes(postBuilder.ToString()); 
       request.ContentLength = postBytes.Length; 
       request.ContentType = "application/x-www-form-urlencoded"; 

       var stream = request.GetRequestStream(); 
       stream.Write(postBytes, 0, postBytes.Length); 
       stream.Close(); 
       stream.Dispose(); 

      } 

      return tmprequest; 
     } 
    } 

使用這樣做:如果u必須創建POST類型請求

class Program 
{ 
    private static void Main() 
    { 
     ExtWebClient webclient = new ExtWebClient(); 
     webclient.PostParam = new NameValueCollection(); 
     webclient.PostParam["param1"] = "value1"; 
     webclient.PostParam["param2"] = "value2"; 

     webclient.DownloadFile("http://www.example.com/myfile.zip", @"C:\myfile.zip"); 
    } 
} 

用途:用於GET類型請求,U可以只需使用普通網絡客戶端

class Program 
{ 
    private static void Main() 
    { 
     WebClient webclient = new WebClient(); 

     webclient.DownloadFile("http://www.example.com/myfile.zip?param1=value1&param2=value2", @"C:\myfile.zip"); 
    } 
} 
+0

非常感謝,您的解決方案完美無缺。在使用HttpWebrequest時,我能夠下載流,但無法將其保存在文件中。而在使用webclient時,我無法將請求類型設置爲Post。你的解決方案結合了兩者 –

+0

你救了我的命!謝謝! – Crasher

-1
string url = @"http://www.microsoft.com/windows8.zip"; 

WebClient client = new WebClient(); 

    client.DownloadFileCompleted += new AsyncCompletedEventHandler(client_DownloadFileCompleted); 

    client.DownloadFileAsync(new Uri(url), @"c:\windows\windows8.zip"); 


void client_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e) 
{ 
    MessageBox.Show("File downloaded"); 
} 
+0

他需要通過post參數下載文件,默認爲GET –

+0

哦,好的。他必須創建一個報告頁面等,這個頁面接受參數,然後返回相關的文件。 – Baris