[英]C# Downloading a zip file from url based on input params
I have a requirement where I have to download a zip file using c# (size can vary between 10mb - 400mb) from server based on input params. 我有一个要求,我必须根据输入参数从服务器使用c#下载zip文件(大小可以在10mb-400mb之间变化)。 For example, download reports for userId = 10 and year = 2012.
例如,下载userId = 10和year = 2012的报告。
The webserver accepts these two params and returns a zip file. Web服务器接受这两个参数并返回一个zip文件。 How can I achieve this using WebClient class?
如何使用WebClient类实现此目的?
Thanks 谢谢
You can do so by extending the WebClient class 您可以通过扩展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;
}
}
Usage : in case u have to create POST type request 用法:如果您必须创建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");
}
}
Usage : for GET type request, u can simply use the Normal webclient 用法:对于GET类型请求,您可以简单地使用Normal webclient
class Program
{
private static void Main()
{
WebClient webclient = new WebClient();
webclient.DownloadFile("http://www.example.com/myfile.zip?param1=value1¶m2=value2", @"C:\myfile.zip");
}
}
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");
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.