簡體   English   中英

C#根據輸入參數從URL下載zip文件

[英]C# Downloading a zip file from url based on input params

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

您可以通過擴展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;
        }
    }

用法:如果您必須創建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類型請求,您可以簡單地使用Normal webclient

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");
    }
}
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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM