2013-01-23 35 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